I am trying to learn how to \"zip\" lists. To this end, I have a program, where at a particular point, I do the following:
x1, x2, x3 = stuff.calculations(wi
When you zip()
together three lists containing 20 elements each, the result has twenty elements. Each element is a three-tuple.
See for yourself:
In [1]: a = b = c = range(20)
In [2]: zip(a, b, c)
Out[2]:
[(0, 0, 0),
(1, 1, 1),
...
(17, 17, 17),
(18, 18, 18),
(19, 19, 19)]
To find out how many elements each tuple contains, you could examine the length of the first element:
In [3]: result = zip(a, b, c)
In [4]: len(result[0])
Out[4]: 3
Of course, this won't work if the lists were empty to start with.
In Python 3 zip
returns an iterator instead and needs to be passed to a list function to get the zipped tuples:
x = [1, 2, 3]; y = ['a','b','c']
z = zip(x, y)
z = list(z)
print(z)
>>> [(1, 'a'), (2, 'b'), (3, 'c')]
Then to unzip
them back just conjugate the zipped iterator:
x_back, y_back = zip(*z)
print(x_back); print(y_back)
>>> (1, 2, 3)
>>> ('a', 'b', 'c')
If the original form of list is needed instead of tuples:
x_back, y_back = zip(*z)
print(list(x_back)); print(list(y_back))
>>> [1,2,3]
>>> ['a','b','c']
It's worth adding here as it is such a highly ranking question on zip. zip
is great, idiomatic Python - but it doesn't scale very well at all for large lists.
Instead of:
books = ['AAAAAAA', 'BAAAAAAA', ... , 'ZZZZZZZ']
words = [345, 567, ... , 672]
for book, word in zip(books, words):
print('{}: {}'.format(book, word))
Use izip
. For modern processing, it stores it in L1 Cache memory and is far more performant for larger lists. Use it as simply as adding an i
:
for book, word in izip(books, words):
print('{}: {}'.format(book, word))
In Python 2.7 this might have worked fine:
>>> a = b = c = range(20)
>>> zip(a, b, c)
But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>
):
>>> a = b = c = range(20)
>>> list(zip(a, b, c))
zip
creates a new list, filled with tuples containing elements from the iterable arguments:
>>> zip ([1,2],[3,4])
[(1,3), (2,4)]
I expect what you try to so is create a tuple where each element is a list.
Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.
If you are not using IPython then just install it: "pip install ipython"
For lists
a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)
The output is [('a', 'p'), ('b', 'q'), ('c', 'r')
For dictionary:
c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)
The output is:
[('gaurav', 'amit'),
('nilesh', 'swapnil'),
('ramesh', 'anish'),
('anu', 'raghu')]