Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does x,y = zip(*zip(a,b)) work in Python?

Tags:

python

OK I love Python's zip() function. Use it all the time, it's brilliant. Every now and again I want to do the opposite of zip(), think "I used to know how to do that", then google python unzip, then remember that one uses this magical * to unzip a zipped list of tuples. Like this:

x = [1,2,3] y = [4,5,6] zipped = zip(x,y) unzipped_x, unzipped_y = zip(*zipped) unzipped_x     Out[30]: (1, 2, 3) unzipped_y     Out[31]: (4, 5, 6) 

What on earth is going on? What is that magical asterisk doing? Where else can it be applied and what other amazing awesome things in Python are so mysterious and hard to google?

like image 338
Mike Dewar Avatar asked Mar 24 '10 20:03

Mike Dewar


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.

How does zip function work in Python?

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.

What is the role of the * operator within the zip () function?

Basically, it passes the contents of the lists as arguments.

What is zip () function in tuple give an example program using zip () function?

The zip() function returns an iterator of tuples based on the iterable objects. If a single iterable is passed, zip() returns an iterator of tuples with each tuple having only one element. If multiple iterables are passed, zip() returns an iterator of tuples with each tuple having elements from all the iterables.


1 Answers

The asterisk in Python is documented in the Python tutorial, under Unpacking Argument Lists.

like image 118
Daniel Stutzbach Avatar answered Oct 10 '22 22:10

Daniel Stutzbach