[(1,2), (2,3), (4,5), (3,4), (6,7), (6,7), (3,8)]
How do I return the 2nd value from each tuple inside this list?
Desired output:
[2, 3, 5, 4, 7, 7, 8]
In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
With a list comprehension.
[x[1] for x in L]
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]
[]
'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 the list
type. Hence, this technique is called a "list comprehension."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 access x
outside of the comprehension, or type type(x)
after executing the above line and it will tell you NameError: name 'x' is not defined
, whereas type(L)
returns <class 'list'>
.x[1]
points to the second item in each of the tuples whereas x[0]
would point to each of the first items.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With