0

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.

4
  • Can you share sample values for list_a and list_b and the result you'd like to get for them? Commented Oct 30, 2016 at 7:04
  • 1
    But the first block of code will give you a syntax error? Can you please clarify? Commented Oct 30, 2016 at 7:04
  • 1
    for i,j in zip(list_a, list_b): print(i+j) Commented Oct 30, 2016 at 7:06
  • 1
    I tried your first code and it gave me IndentationError: expected an indented block. What code are you actually running? Commented Oct 30, 2016 at 7:09

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.