user3476378 user3476378 - 3 months ago 28
Python Question

For Loop | Python

I am using Python first time for web scraping and while doing a code, I got stuck into a for loop.

As we can see, both b and a returns a list. I am using for loop to iterate over the list values of both b and a, and print it in like a sequence :

Desired Output

first value of b, first value of a, second value of b, second value of a....

Here is the code :

b = soup.find("module", {"type":"Featured Link List Advanced"}).find_all("span")

a = soup.find("module", {"type":"Featured Link List Advanced"}).find("ul").find_all("a")\

for i in b:
print (i.string)
for j in a:
print (j.get("href"))

But the output I am getting is :

First value of b, First value of a, second value of b, first value of a, third value of, first value of a,

Can some help me in getting the desired output ? I know I am missing something.

Answer Source

Use built-in zip to iterate over 2 sequences in parallel:

for (i,j) in zip(b,a):
   print (i.string)
   print (j.get("href"))