Linda Su
Linda Su

Reputation: 455

How to extract only the first element of each element in a list of lists?

I have a list like this:

[[1, 2], [5, 3], [7, 2]]

I want to extract the first of each element, i.e., get an output like this:

[1,5,7]

How to do that?

Upvotes: 0

Views: 781

Answers (3)

Hackaholic
Hackaholic

Reputation: 19733

using list comprehension:

my_list = [[1, 2], [5, 3], [7, 2]]
my_new_list = [ x[0] for x in my_list ]

demo:

>>> my_list = [[1, 2], [5, 3], [7, 2]]
>>> my_list[0]
[1,2]
>>> my_list[0][0]
1

simple without list comprehension:

my_list = [[1, 2], [5, 3], [7, 2]]
my_new_list = []
for x in my_list:
    my_new_list.append(x[0])

using lambda and map:

# python 2x
my_new_list = map(lambda x:x[0],my_list)
#python 3x
my_new_list = list(map(lambda x:x[0],my_list))

Upvotes: 1

Marcus McLean
Marcus McLean

Reputation: 1326

Use a list comprehension:

my_list = [[1, 2], [5, 3], [7, 2]]
new_list = [x[0] for x in my_list]

Upvotes: 1

Adam Smith
Adam Smith

Reputation: 54163

Use a list comprehension. For instance:

old_list = [[1,2], [5,3], [7,2]]
new_list = [sublist[0] for sublist in old_list]

Alternatively you can use map with operator.itemgetter.

import operator

old_list = [[1,2], [5,3], [7,2]]
new_list = map(operator.itemgetter(0), old_list)
## in python3
# new_list = list(map(operator.itemgetter(0), old_list))

Upvotes: 1

Related Questions