Reputation: 455
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
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
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
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