Justin
Justin

Reputation: 49

Take values in a tuple list and put in another list?

say I have a list of tuples. I want to put the second element of all tuples in their own list while preserving the original order. Are there any quick and dirty ways to do this?

example before sorting.

[(0,'apple'),
(1,'pineapple'),
(11,'cherry'),
(12,'banana'),
(13,'mango'),
(14,'boot'),
(15,'mangosteen')]

after sorting

['apple',
'pineapple',
'cherry',
'banana',
'mango',
'boot',
'mangosteen']

Upvotes: 1

Views: 104

Answers (2)

dawg
dawg

Reputation: 103754

You essentially just need to map the operation of getting the element at index 1 of each tuple in a list and produce a new list.

Given:

>>> LoT
[(0, 'apple'), (1, 'pineapple'), (11, 'cherry'), (12, 'banana'), (13, 'mango'), (14, 'boot'), (15, 'mangosteen')]

You can use a list comprehension and access the element of interest of each tuple:

>>> [t[1] for t in LoT]
['apple', 'pineapple', 'cherry', 'banana', 'mango', 'boot', 'mangosteen']

You can use tuple unpacking:

>>> [b for _,b in LoT]
['apple', 'pineapple', 'cherry', 'banana', 'mango', 'boot', 'mangosteen']

Which fails if the tuple is anything but 2 elements long.

Alternatively, you can use zip:

>>> list(zip(*LoT))[1]
('apple', 'pineapple', 'cherry', 'banana', 'mango', 'boot', 'mangosteen')

You can use an itemgetter with map:

>>> list(map(itemgetter(1),LoT))
['apple', 'pineapple', 'cherry', 'banana', 'mango', 'boot', 'mangosteen']

With Python3 you need to use list around zip to subscript the first element or around map to show it. Combined with loops or other flow contol in Python 3, you likely would not need that.

The first, [t[1] for t in LoT], is the most idiomatic and the last, map(itemgetter(1),LoT) may be the fastest.

Upvotes: 3

user8594856
user8594856

Reputation:

Tuple unpacking as an alternative.

[b for a,b in lst]

Upvotes: 2

Related Questions