Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking a list / tuple of pairs into two lists / tuples

People also ask

How do you split a tuple into two lists?

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.

How do I unpack a list of tuples?

If you want to unzip your list of tuples, you use the combination of zip() method and * operator.

Does tuple unpacking work with lists?

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 [] .

Is unpacking possible in a tuple?

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)