Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

zip

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?

like image 721
Jim Avatar asked May 09 '11 15:05

Jim


People also ask

What is zip (* data in Python?

Python's zip() function is defined as zip(*iterables) . The function takes in iterables as arguments and returns an iterator. This iterator generates a series of tuples containing elements from each iterable. zip() can accept any type of iterable, such as files, lists, tuples, dictionaries, sets, and so on.

Can we zip three lists?

Python zip three lists Python zipping of three lists by using the zip() function with as many inputs iterables required. The length of the resulting tuples will always equal the number of iterables you pass as arguments. This is how we can zip three lists in Python.

What does * do in zip?

The "*" operator unpacks a list and applies it to a function. The zip function takes n lists and creates n-tuple pairs from each element from both lists: zip([iterable, ...]) This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.


2 Answers

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

zip(assignment, *grades)
like image 160
sth Avatar answered Oct 02 '22 14:10

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))
like image 21
jmil166 Avatar answered Oct 02 '22 14:10

jmil166