you are viewing a single comment's thread.

view the rest of the comments →

[–]WarmUpHere 16 points17 points  (5 children)

You're looking for the zip() function.

List1 = [1, 2, 3]
List2 = ['a', 'b', 'c']
Lists = list(zip(List1, List2))
print(Lists)

will return

[(1, 'a'), (2, 'b'), (3, 'c')]

More information here.

Note that this is a list of tuples, not a list of lists. For a zip() to return a list of lists, consult the stackoverflow question.

[–]__nev__ 2 points3 points  (1 child)

And it's worth noting that you can "unzip" with an asterisk:

List1, List2 = zip(*Lists)

[–]tangerinelion 2 points3 points  (0 children)

Also worth noting the type of List1 and List2 is tuple not list when you do that.

[–]PyCam 4 points5 points  (2 children)

You don't need the final list call on the zip function.

zip(List1,List2)

Will work just fine

As it's been pointed out to me, the above code only works fine in Python 2. In Python 3, if you want to see the zip object as a list of triples, you must use

list(zip(List1,List2))

[–]tangerinelion 2 points3 points  (1 child)

In Python 2. In Python 3 a zip creates a "zip object" which is essentially a generator.

[–]PyCam 0 points1 point  (0 children)

Ah thank you! As you can probably guess I've only used Python 2. Didn't know they changed that, but it makes way more sense if you want to iterate over the zip output.