Accessing a value in a tuple that is in a list
Ignacio's answer is what you want. However, as someone also learning Python, let me try to dissect it for you... As mentioned, it is a list comprehension (covered in DiveIntoPython3, for example). Here are a few points:
[x[1] for x in L]
- Notice the
[]
's around the line of code. These are what define a list. This tells you that this code returns a list, so it's of thelist
type. Hence, this technique is called a "list comprehension." - L is your original list. So you should define
L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
prior to executing the above code. x
is a variable that only exists in the comprehension - try to accessx
outside of the comprehension, or typetype(x)
after executing the above line and it will tell youNameError: name 'x' is not defined
, whereastype(L)
returns<class 'list'>
.x[1]
points to the second item in each of the tuples whereasx[0]
would point to each of the first items.- So this line of code literally reads "return the second item in a tuple for all tuples in list L."
It's tough to tell how much you attempted the problem prior to asking the question, but perhaps you just weren't familiar with comprehensions? I would spend some time reading through Chapter 3 of DiveIntoPython, or any resource on comprehensions. Good luck.
A list comprehension is absolutely the way to do this. Another way that should be faster is map
and itemgetter
.
import operator
new_list = map(operator.itemgetter(1), old_list)
In response to the comment that the OP couldn't find an answer on google, I'll point out a super naive way to do it.
new_list = []
for item in old_list:
new_list.append(item[1])
This uses:
- Declaring a variable to reference an empty list.
- A for loop.
- Calling the
append
method on a list.
If somebody is trying to learn a language and can't put together these basic pieces for themselves, then they need to view it as an exercise and do it themselves even if it takes twenty hours.
One needs to learn how to think about what one wants and compare that to the available tools. Every element in my second answer should be covered in a basic tutorial. You cannot learn to program without reading one.
With a list comprehension.
[x[1] for x in L]