I have a list of 2-item tuples and I'd like to convert them to 2 lists where the first contains the first item in each tuple and the second list holds the second item.
For example:
original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)] # and I want to become... result = (['a', 'b', 'c', 'd'], [1, 2, 3, 4])
Is there a builtin function that does that?
unzip() just opposite of zip(), means convert the zipped values back to their initial form and this done with the help of the '*' operator.
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.
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.
zip
is its own inverse! Provided you use the special * operator.
>>> zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)]) [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
The way this works is by calling zip
with the arguments:
zip(('a', 1), ('b', 2), ('c', 3), ('d', 4))
… except the arguments are passed to zip
directly (after being converted to a tuple), so there's no need to worry about the number of arguments getting too big.
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