I am new to Python. Imagine we have a list like this: [(1,0.2), (2,4.8), (5,5.6)] I want to fetch the all left side elements so that I have a list like this: [1,2,5] I am wondering how I can do that. Thanks
-
1Welcome to Stack Overflow! You seem to be asking for someone to write some code for you. Stack Overflow is a question and answer site, not a code-writing service. Please [see here](http://stackoverflow.com/help/how-to-ask) to learn how to write effective questions. – Morgan Thrapp Nov 09 '15 at 15:47
-
`[i[0] for i in lst]` – Avinash Raj Nov 09 '15 at 15:48
3 Answers
You can use a list comprehension statement like:
example = [(1,0.2), (2,4.8), (5,5.6)]
[x[0] for x in example]
which basically iterates through all your elements, and grabs the first element in each tuple, and creates a new array out of it.

- 6,929
- 1
- 17
- 47
m = [(1,0.2), (2,4.8), (5,5.6)]
out_list = []
for element in m:
out_list.append(element[0])
print out_list
You have to navigate thru all the elements
of m
, then, take the first number with element[0]
and append it to a new list titled out_list
The code will output
[1,2,5]
You can you this on a more ellegant way using list comprehension as follows:
out_list = [element[0] for element in m ]
print out_list

- 7,963
- 11
- 64
- 105
Most people suggest list comprehension as the solution to your problem, which is great. But python can do the same thing via different approaches. Recently I learnt how to "unzip" a list and the technique fits right into your problem.
zipped = [(1,0.2), (2,4.8), (5,5.6)]
list(zip(*zipped)[0])
In this thread, people explained how it works. Hope you will get something from it. Welcome to the python world!