0

I have two lists:

odd_numbers = [1, 3, 5, 7]
evennumber = [2, 4, 6, 8]

I expect to print the below:

result = [1,2,3,4,5,6,7,8]

basically, picking up value from each list and concatenating them. I tried the below list comprehension that worked but i didn't understand the usage of for twice. Can some please explain:

y = [a for x in zip(odd_numbers, evennumber) for a in x]
print(y)

Also, if i wish to achieve the same output [1, 2, 3, 4, 5, 6, 7, 8], how can i do it with for loops?

Natan
  • 71
  • 5
  • 2
    I understand your question but I don't think two `for` loops is going to do what you want. Think of two loops as going over a square, like a chess board. `for row in rows: ... for column in columns: ...` In this case, you have two "rows". You only want to loop down them once, alternating what to pluck from. Unfortunately, some Stack Overflow moderator was very Stack Overflowy and just read your title and not your problem and closed it as a duplicate, but let me know if this question gets re-opened and I'll try to illustrate better the problem with using two `for` loops for this. – user1717828 Jun 27 '20 at 16:32
  • Because you get a list of tuples from `zip` and that list is then flattened as [here](https://stackoverflow.com/a/952952/298607) – dawg Jun 28 '20 at 00:37
  • To do this with a `for` loop, you can do: `new_list=[]; for x,y in zip(odd_numbers, evennumber): new_list.extend([x,y])` – dawg Jun 28 '20 at 00:42

1 Answers1

1

zip will return an iterator over tuple of the elements at the same index in both lists. This should help in understanding

list(zip(odd_numbers, evennumber))

returns [(1, 2), (3, 4), (5, 6), (7, 8)]

So the first for loop iterates over this iterator returned by zip. The second for loop gets one tuple at a time. If you switch the positions of evennumber and odd_numbers in the zip you would get the following result.

[2, 1, 4, 3, 6, 5, 8, 7]

I hope this clarifies the usage of the for loops here.

pecey
  • 651
  • 5
  • 13