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
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.
I don't think zip
returns a list. zip
returns a generator. You have got to do list(zip(a, b))
to get a list of tuples.
x = [1, 2, 3]
y = [4, 5, 6]
zipped = zip(x, y)
list(zipped)
Source: My Blog Post (better formatting)
Example
numbers = [1,2,3]
letters = 'abcd'
zip(numbers, letters)
# [(1, 'a'), (2, 'b'), (3, 'c')]
Zero or more iterables [1] (ex. list, string, tuple, dictionary)
1st tuple = (element_1 of numbers, element_1 of letters)
2nd tuple = (e_2 numbers, e_2 letters)
…
n-th tuple = (e_n numbers, e_n letters)
i
th tuple = (element_i arg1, element_i arg2…, element_i argn
)1) Empty String: len(str)= 0 = no tuples
2) Single String: len(str) == 2 tuples with len(args) == 1 element(s)
zip()
# []
zip('')
# []
zip('hi')
# [('h',), ('i',)]
1. Build a dictionary [2] out of two lists
keys = ["drink","band","food"]
values = ["La Croix", "Daft Punk", "Sushi"]
my_favorite = dict( zip(keys, values) )
my_favorite["drink"]
# 'La Croix'
my_faves = dict()
for i in range(len(keys)):
my_faves[keys[i]] = values[i]
zip
is an elegant, clear, & concise solution2. Print columns in a table
"*" [3] is called "unpacking": f(*[arg1,arg2,arg3]) == f(arg1, arg2, arg3)
student_grades = [
[ 'Morty' , 1 , "B" ],
[ 'Rick' , 4 , "A" ],
[ 'Jerry' , 3 , "M" ],
[ 'Kramer' , 0 , "F" ],
]
row_1 = student_grades[0]
print row_1
# ['Morty', 1, 'B']
columns = zip(*student_grades)
names = columns[0]
print names
# ('Morty', 'Rick', 'Jerry', 'Kramer')
zip(*args)
is called “unzipping” because it has the inverse effect of zip
numbers = (1,2,3)
letters = ('a','b','c')
zipped = zip(numbers, letters)
print zipped
# [(1, 'a'), (2, 'b'), (3, 'c')]
unzipped = zip(*zipped)
print unzipped
# [(1, 2, 3), ('a', 'b', 'c')]
unzipped
: tuple_1 = e1 of each zipped tuple. tuple_2 = e2 of each zipped
*
Code:
# foo - function, returns sum of two arguments
def foo(x,y):
return x + y
print foo(3,4)
# 7
numbers = [1,2]
print foo(numbers)
# TypeError: foo() takes exactly 2 arguments (1 given)
print foo(*numbers)
# 3
*
took numbers
(1 arg) and “unpacked” its’ 2 elements into 2 args
For the completeness's sake.
When zipped lists' lengths are not equal. The result list's length will become the shortest one without any error occurred
>>> a = [1]
>>> b = ["2", 3]
>>> zip(a,b)
[(1, '2')]