17

I have a list of many 2-tuples. I would like to split the list into two lists, one list consisting of the first elements of all the tuples in the list, and the other list consisting of the second elements of all the tuples. I wonder how to do that efficiently? Thanks!

For example, I have a list 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].

6 Answers6

62
a,b = zip(*y)

is all you need ...

or if you need them as lists and not tuples

a,b = map(list,zip(*y))
Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
8

zip with * argument unpacking will give you tuples:

>>> a, b = zip(*y)
>>> a
('ab', 'cd', 'ef')
>>> b
(1, 2, 3)

If you need lists, you can use map on that:

>>> a, b = map(list, zip(*y))
>>> a
['ab', 'cd', 'ef']
>>> b
[1, 2, 3]
mhlester
  • 22,781
  • 10
  • 52
  • 75
6

Use zip and a list comprehension:

>>> y = [('ab', 1), ('cd', 2), ('ef', 3)]
>>> a,b = [list(c) for c in zip(*y)]
>>> a
['ab', 'cd', 'ef']
>>> b
[1, 2, 3]
>>>
0

try this:

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)
pianist1119
  • 319
  • 1
  • 8
  • 19
0

One way to do it is first convert the list into a temp dictionary, then assign the keys & values of the temp dictionary into 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
jeremy
  • 4,294
  • 3
  • 22
  • 36
lessthanl0l
  • 1,035
  • 2
  • 12
  • 21
  • 1
    Note that this will only work in Python 2.x. In Python 3.x, `dict.keys` and `dict.values` return [view objects](http://docs.python.org/3/glossary.html#view). –  Feb 18 '14 at 23:51
  • Didn't know that. How would you modify the code using this technique? – lessthanl0l Feb 19 '14 at 00:14
  • 1
    You need to explicitly convert the view objects into lists. In other words, you would do this `list1 = list(temp_d)` and then this `list2 = list(temp_d.values())`. Notice too that I removed the call to `dict.keys` in the first example. It is no longer needed since iterating over a dictionary yields its keys. Finally, you only need to do this if you are using Python 3.x. In Python 2.x, your current code would work fine because `dict.keys` and `dict.values` return lists. –  Feb 19 '14 at 00:25
0
l1 = []
l2 = []
for i in y:
    l1.append(i[0])
    l2.append(i[1])
l1
    ['ab', 'cd', 'ef']
l2
    [1, 2, 3]

Appending each value into another

nucsit026
  • 652
  • 7
  • 16
rajpython
  • 179
  • 2
  • 3
  • 14