Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between zip(list) and zip(*list) [duplicate]

I am using a list p = [[1,2,3],[4,5,6]]

If I do :

>>>d=zip(p) >>>list(d) [([1, 2, 3],), ([4, 5, 6],)] 

Though, what I actually want is obtained using this:

>>>d=zip(*p) >>>list(d) [(1, 4), (2, 5), (3, 6)] 

I have found out that adding a '*' before the list name gives my required output, but I can't make out the difference in their operation. Can you please explain the difference?

like image 411
user3735438 Avatar asked Mar 19 '15 07:03

user3735438


People also ask

What does zip (* list do 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.

Does zip remove duplicates?

Answer. If the list passed to the zip() function contains duplicate data, the duplicate created as part of the list comprehension will be treated as an update to the dictionary and change the value associated with the key. No error will be reported.

What does zip and * operator do?

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.

What is the use of zip () and zip *?

The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

Can you zip more than 2 lists Python?

The Python zip() function makes it easy to also zip more than two lists. This works exactly like you'd expect, meaning you just only need to pass in the lists as different arguments.


1 Answers

zip wants a bunch of arguments to zip together, but what you have is a single argument (a list, whose elements are also lists). The * in a function call "unpacks" a list (or other iterable), making each of its elements a separate argument. So without the *, you're doing zip( [[1,2,3],[4,5,6]] ). With the *, you're doing zip([1,2,3], [4,5,6]).

like image 114
Sneftel Avatar answered Sep 20 '22 22:09

Sneftel