To split a tuple, just list the variable names separated by commas on the left-hand side of an equals sign, and then a tuple on the right-hand side.
If you want to unzip your list of tuples, you use the combination of zip() method and * operator.
Unpack a nested tuple and list. You can also unpack a nested tuple or list. If you want to expand the inner element, enclose the variable with () or [] .
In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments. “*_” is used to specify the arbitrary number of arguments in the tuple.
>>> source_list = [('1','a'),('2','b'),('3','c'),('4','d')]
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')
Edit: Note that zip(*iterable)
is its own inverse:
>>> list(source_list) == zip(*zip(*source_list))
True
When unpacking into two lists, this becomes:
>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True
Addition suggested by rocksportrocker.
list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)
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