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?
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.
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.
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.
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.
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)]
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