I have a list of 2 tuples. I would like to split the list into two lists, one list consisting of the first elements of all tuples in the list, and the other list consists of the second elements of all tuples. I wonder how to do it effectively? Thanks!
For example, I have a list y :
y
>>> y = [('ab',1), ('cd', 2), ('ef', 3) ] >>> type(y) <type 'list'>
I hope to get two lists ['ab', 'cd', 'ef'] and [1, 2, 3] .
['ab', 'cd', 'ef']
[1, 2, 3]
a,b = zip(*y)
- thatβs all you need ...
or if you need them as lists, not tuples
a,b = map(list,zip(*y))
Use zip and list :
zip
>>> y = [('ab', 1), ('cd', 2), ('ef', 3)] >>> a,b = [list(c) for c in zip(*y)] >>> a ['ab', 'cd', 'ef'] >>> b [1, 2, 3] >>>
zip with unpacking arguments * will give you tuples:
*
>>> a, b = zip(*y) >>> a ('ab', 'cd', 'ef') >>> b (1, 2, 3)
If you need lists, you can use map :
>>> a, b = map(list, zip(*y)) >>> a ['ab', 'cd', 'ef'] >>> b [1, 2, 3]
try the following:
def get_list(tuples): list1 = [] list2 = [] for i in tuples: list1.append(i[0]) list2.append(i[1]) return list1, list2 y = [('ab',1), ('cd', 2), ('ef', 3) ] letters, numbers = get_list(y)
One way to do this is to first convert the list to a temp dictionary, then assign the keys and values ββof the temp dictionary to two lists
y = [('ab', 1), ('cd', 2), ('ef', 3)] temp_d = dict(y) list1 = temp_d.keys() list2 = temp_d.values() print list1 print list2
l1 = [] l2 = [] for i in y: l1.append(i[0]) l2.append(i[1])
l1 ['ab', 'cd', 'ef'] l2 [1, 2, 3]
Adding each value to another