How would you zip an unknown number of lists in Python?

Question:

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?

Asked By: Jim

||

Answers:

You can use * to unpack a list into positional parameters:

zip(assignment, *grades)
Answered By: sth

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))
Answered By: jmil166
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.