Reputation: 11379
Let's say I have the following lists:
assignment = ['Title', 'Project1', 'Project2', 'Project3']
grades = [ ['Jim', 45, 50, 55], \
['Joe', 55, 50, 45], \
['Pat', 55, 60, 65] ]
I could zip the lists using the following code:
zip(assignment, grades[0], grades[1], grades[2])
How would I use the zip function to zip this if the grades list contains an unkown number of items?
Upvotes: 38
Views: 12812
Reputation: 11
Adding to sth's answer above, unpacking allows you to pass in your function parameters as an array rather than multiple parameters into the function. The following example is given in documentation:
list(range(3, 6)) # normal call with separate arguments
[3, 4, 5]
args = [3, 6]
list(range(*args)) # call with arguments unpacked from a list
[3, 4, 5]
In the case of zip()
this has been extremely handy for me as I'm putting together some logic that I want to be flexible to the number of dimensions in my data. This means first collecting each of these dimensions in an array and then providing them to zip()
with the unpack operator.
myData = []
myData.append(range(1,5))
myData.append(range(3,7))
myData.append(range(10,14))
zippedTuple = zip(*myData)
print(list(zippedTuple))
Upvotes: 1