2

I am sure this is a very basic question and I have checked the web for answers but alas none has come up.

I am learning python 3.5 and I have installed Anaconda. I am trying to learn about and use the built-in function zip() but when I type something like (in my Jupiter notebook)

a = [1,2,3]
b = [4,5,6]
zip(a,b)

I get <zip at 0xXXXXX>as the output, where XXXXX is some (random) set of characters. I was expecting

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

as the output. Is there something wrong or are my expectations incorrect?

Thanks in advance!

Richard
  • 63
  • 5

2 Answers2

4

In python 3 zip returns an iterator over the zipped values, use:

for x, y in zip(a, b):
    print(x, y)
Bahrom
  • 4,752
  • 32
  • 41
4

In python 3 you nearly always get a generator object from operations such as zip or range.

This produces less memory overhead, as no big iterable is created, holding all the needed values.

If you want to get the list, call list on the generator.

>>> l = list(zip([1, 2, 3], [4, 5, 6]))

However, this will give you a list of tuples:

>>> l
[(1, 4), (2, 5), (3, 6)] 

If you want to get a list of lists, use a list comprehension:

>>> l = [list(t) for t in zip([1, 2, 3], [4, 5, 6])] 
MaxNoe
  • 14,470
  • 3
  • 41
  • 46