Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible variants of zip in Python

Tags:

python

list

For example, I have a code looks like this:

a = [1, 2] b = [4, 5] 

How can I get something like this:

[(1,4), (1,5), (2,4), (2,5)] 

Like function zip does, but with all possible variants. Or can't I?

like image 373
alexvassel Avatar asked Feb 05 '11 14:02

alexvassel


People also ask

How many lists can you zip Python?

Python zip list of lists. Python zip list of lists defines three different lists with the same number of items and passes those lists to the zip() method, which will return the tuple iterator and then convert it into the list using the list() method.

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.

What is zip () in Python?

Python zip() Function 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.

How do I zip a list in Python?

Use zip() Function to Zip Two Lists in Python Python has a built-in function known as zip() . The zip() function can take any iterable as its argument. It's used to return a zip object which is also an iterator. The returned iterator is returned as a tuple like a list, a dictionary, or a set.


1 Answers

You want itertools.product:

>>> import itertools >>> a = [1,2] >>> b = [4,5] >>> list(itertools.product(a,b)) [(1, 4), (1, 5), (2, 4), (2, 5)] 
like image 149
DSM Avatar answered Oct 08 '22 17:10

DSM