Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a value in a tuple that is in a list

[(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] 
like image 278
super9 Avatar asked Jan 26 '11 02:01

super9


People also ask

How do you access each element in a list of tuples?

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.

How do you get a tuple from a list?

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.


2 Answers

With a list comprehension.

[x[1] for x in L] 
like image 88
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 11:09

Ignacio Vazquez-Abrams


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.

like image 29
gary Avatar answered Sep 20 '22 11:09

gary