Yuyun He
Yuyun He

Reputation: 5

Nested for loop python

I want to print items from two lists respectively. I wrote code as below:

 for i in list_a:
     for j in list_b:
     print(str(i) + str(j))

The ideal result would be "A1 + B1", "A2 + B2", etc. However, the lines above only field the last item in list_b. When I indent the print statement further:

for i in list_a:
    for j in list_b:
        print(str(i) + str(j))

The result does not seem to be correct. I know this is a really basic for loop question, but I am very confused by the ways the outputs differ.

Upvotes: 0

Views: 100

Answers (2)

Ross Drew
Ross Drew

Reputation: 8246

I'm adding another answer because no one has explained why this code doesn't work. Which seems to me what the OP was actually looking for.

Your Solution 1:

for i in list_a:
     #This indentation is inside 'i' loop
     for j in list_b:
          #This indentation is inside 'j' loop  
     print(str(i) + str(j))

Will step through list_a, and for every iteration, step through all of list_b (as there's nothing in the list_b code block, nothing will happen for each step) THEN print, so it will print out for every i in list_a and j will always be the number of the last item of list_b as it's stepped through the whole thing.

Although this code probably will not run anyway as there is an empty code block and the compiler will likely pick that up with an IndentationError

Your Solution 2:

for i in list_a:
    for j in list_b:
        print(str(i) + str(j))

Will step through all of list_a and for each element, step through all of list_b so you will end up with A1B1, A1B2, A1B3, etc`.

Preferred Solution

The solution is to step through both lists at the same time, at the same rate which this answer covers nicely, with essentially the same solution as @Pavlins answer.

Upvotes: 1

Pavlin
Pavlin

Reputation: 5528

How about using zip?

for a, b in zip(list_a, list_b):
    print('%s + %s' % (a, b))

Zip merges two or more lists together into tuples, e.g.:

zip([1, 2, 3], [4, 5, 6]) # [(1, 4), (2, 5), (3, 6)]

Also, when you do print(a + b), you simply add the strings together, which means concat. E.g. if a was "a" and b was "b", a + b would produce "ab" and not "a + b" like you wanted.

Upvotes: 4

Related Questions