Accessing a value in a tuple that is in a list
Asked Answered
G

6

97
[(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]
Gilroy answered 26/1, 2011 at 2:3 Comment(0)
P
111

With a list comprehension.

[x[1] for x in L]
Prothallus answered 26/1, 2011 at 2:5 Comment(5)
I understand this is a simple question. Is SO such an elitist place? Try googling the question, the results are not what I need. I did learning python the hard way and i didn't find this in there. I've asked questions before about the the best approach to learning Python and the unanimous answer is to get a basic book and just dive in. It frustrates me as well as I just cannot find the solution in any book or online material I have search for so far? Plus your comment really isn't helpful and discourages newbies new members from posting on SO.Gilroy
@Nai: I suggest to read the Python tutorial: docs.python.org/tutorial/index.html . In general, the documentation is very good. And sometimes, one just has to try ;)Parsimony
I Googled "accessing item in tuple" with the intent of accessing an item in a tuple list. It brought me to your question so thank you. I am fairly new to Python and don't find the answer particularly intuitive, but that's just me!Grani
I thought the entire concept with SO was to make it easier to find answers to your questions. Why must a question be of a certain difficulty in order to be valid? Good question, good answer.Bowerman
Brilliant! A short, sharp, to the point answer to a short, sharp, to the point question. You both just made my day!Crossbow
R
85

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 the list 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 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.
  • 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.

Remit answered 26/1, 2011 at 4:13 Comment(3)
In 2.x, x will exist outside of the LC, with the last value bound to it. This is fixed in 3.x.Prothallus
Awesome explanation @gary. I appreciate especially your pointing out what L refers to.Grani
Thanks for the feedback @PatrickWilliams. I'm glad this helps. You could also do [x[1] for x in [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]] but it's not as easy on the eyes.Remit
O
5

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:

  1. Declaring a variable to reference an empty list.
  2. A for loop.
  3. 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.

Odonto answered 26/1, 2011 at 5:24 Comment(0)
P
2

You can also use sequence unpacking with zip:

L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]

_, res = zip(*L)

print(res)

# (2, 3, 5, 4, 7, 7, 8)

This also creates a tuple _ from the discarded first elements. Extracting only the second is possible, but more verbose:

from itertools import islice

res = next(islice(zip(*L), 1, None))
Pretrice answered 10/9, 2018 at 10:57 Comment(0)
U
2

OR you can use pandas:

>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0    2
1    3
2    5
3    4
4    7
5    7
6    8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>> 

Or numpy:

>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>> 
Unitary answered 10/9, 2018 at 23:30 Comment(0)
G
0
a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))
Gushy answered 12/7, 2020 at 18:19 Comment(1)
Please explain your answer a bit so it gets easier to understand for others searching for it.Ambrosane

© 2022 - 2024 — McMap. All rights reserved.