38

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?

0

2 Answers 2

61

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

zip(assignment, *grades) 
Sign up to request clarification or add additional context in comments.

3 Comments

could you please elaborate? Can you add an assignment? Otherwise this doesn't make sense.
How to use this in a for loop? for ass, grades_ in zip(assignment, *grades) won't know how to unpack.
@Gulzar for t in zip(assignment, *grades) where t is a tuple
1

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)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.