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]
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
super9
  • 29,181
  • 39
  • 119
  • 172

6 Answers6

112

With a list comprehension.

[x[1] for x in L]
Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • 60
    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. – super9 Jan 26 '11 at 02:19
  • 1
    @Nai: I suggest to read the Python tutorial: http://docs.python.org/tutorial/index.html . In general, the documentation is very good. And sometimes, one just has to try ;) – Felix Kling Jan 26 '11 at 02:24
  • 21
    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! – Patrick Williams Mar 31 '16 at 19:44
  • 8
    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. – Sceluswe Oct 04 '16 at 19:13
  • 3
    Brilliant! A short, sharp, to the point answer to a short, sharp, to the point question. You both just made my day! – Eric M May 05 '17 at 18:28
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.

gary
  • 4,227
  • 3
  • 31
  • 58
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.

aaronasterling
  • 68,820
  • 20
  • 127
  • 125
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))
jpp
  • 159,742
  • 34
  • 281
  • 339
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]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0
a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))
David Buck
  • 3,752
  • 35
  • 31
  • 35
Rashmi
  • 1