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?
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.
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.
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.
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.
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.
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])
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With