0

I was seeking a solution for Pythonic way to combine two lists in an alternating fashion? And I came across this elegant solution by @Someone.

[x for y in zip(list1, list2) for x in y]

It works like a charm, but I do not understand how the variables x and y are being assigned here. What is really going on in the list comprehension?

Tian
  • 712
  • 9
  • 22
  • The linked duplicate explains how the variables work in list comprehensions, they work the same as for-loops, essentially – juanpa.arrivillaga Jul 22 '20 at 08:06
  • Note, this is pretty much the equivalent of `from itertools import chain` then `list(chain.from_iterable(zip(list1, list2)))` – juanpa.arrivillaga Jul 22 '20 at 08:07
  • I don't quite agree that this is a duplicate question. The double iteration of the variables makes things a little more complex than the standard one liner if else statement. Nonetheless, I understand now from the link, thanks for that! Never knew that list comprehension could be so powerful – Tian Jul 23 '20 at 05:58

0 Answers0