Zip Lists in Python
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...
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(withdataa)
This gives me three lists, x1, x2, and x3, each of, say, size 20.
Now, I do:
zipall = zip(x1, x2, x3)
However, when I do:
print "len of zipall %s" % len(zipall)
I get 20, which is not what I expected. I expected three. I think I am doing something fundamentally wrong.
10 Answers
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.
zip takes a bunch of lists likes
a: a1 a2 a3 a4 a5 a6 a7...
b: b1 b2 b3 b4 b5 b6 b7...
c: c1 c2 c3 c4 c5 c6 c7...
and "zips" them into one list whose entries are 3-tuples (ai, bi, ci). Imagine drawing a zipper horizontally from left to right.
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.
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']
Source: My Blog Post (better formatting)
Example
numbers = [1,2,3]
letters = 'abcd'
zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]
Input
Zero or more iterables [1] (ex. list, string, tuple, dictionary)