Yuyun He Yuyun He - 1 month ago 5
Python Question

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.

Answer

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.