Reference an Element in a List of Tuples
Asked Answered
B

8

25

Sorry in advance, but I'm new to Python. I have a list of tuples, and I was wondering how I can reference, say, the first element of each tuple within the list. I would think it's something like

for i in number_of_tuples :
  first_element = myList[i[0]]

you know, [list_element[tuple_element]]? However, this doesn't appear to be the right approach. Any help would be greatly appreciated.

Thanks,

Turner

Bergstrom answered 23/6, 2011 at 13:32 Comment(1)
myList[i][0] or more fun: [i[0] for i in myList]Recommendation
S
48

All of the other answers here are correct but do not explain why what you were trying was wrong. When you do myList[i[0]] you are telling Python that i is a tuple and you want the value or the first element of tuple i as the index for myList.

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.

This is a quick rudimentary example that I came up with:

info = [ ( 1, 2), (3, 4), (5, 6) ]

info[0][0] == 1
info[0][1] == 2
info[1][0] == 3
info[1][1] == 4
info[2][0] == 5
info[2][1] == 6
Sooty answered 23/6, 2011 at 15:25 Comment(1)
I wonder whether this answer has a higher computational cost than the list comprehension answer? The latter certainly has a higher memory cost!Selfimmolating
R
31

You can get a list of the first element in each tuple using a list comprehension:

>>> my_tuples = [(1, 2, 3), ('a', 'b', 'c', 'd', 'e'), (True, False), 'qwerty']
>>> first_elts = [x[0] for x in my_tuples]
>>> first_elts
[1, 'a', True, 'q']
Rumpus answered 23/6, 2011 at 13:34 Comment(3)
what if I want to access all the elements of the tuple, like I have a list = [(1,2), (3,4) ,(5,6)]. I want to get 1, 2 both and then 3,4 and so on.. And not just the first or the last element.Buckthorn
@Buckthorn for x in my_tuples...?Rumpus
#27454890Infringement
A
5

The code

my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
    print t

prints

(1, 2)
(3, 4)
(5, 6)

The loop iterates over my_list, and assigns the elements of my_list to t one after the other. The elements of my_list happen to be tuples, so t will always be a tuple. To access the first element of the tuple t, use t[0]:

for t in my_list:
    print t[0]

To access the first element of the tuple at the given index i in the list, you can use

print my_list[i][0]
Annoying answered 23/6, 2011 at 13:43 Comment(2)
is this for python 2? If so is there a similar version for python 3Taboret
@Taboret This is Python 2. In Python 3, simply call print() with parentheses, everything else in this answer remains unchanged.Annoying
T
4

You also can use itemgetter operator:

from operator import itemgetter
my_tuples = [('c','r'), (2, 3), ('e'), (True, False),('text','sample')]
map(itemgetter(0), my_tuples)
Taxidermy answered 23/6, 2011 at 14:4 Comment(0)
Z
3

Rather than:

first_element = myList[i[0]]

You probably want:

first_element = myList[i][0]
Zabrina answered 23/6, 2011 at 13:46 Comment(0)
F
1

So you have "a list of tuples", let me assume that you are manipulating some 2-dimension matrix, and, in this case, one convenient interface to accomplish what you need is the one numpy provides.

Say you have an array arr = numpy.array([[1, 2], [3, 4], [5, 6]]), you can use arr[:, 0] to get a new array of all the first elements in each "tuple".

Faddish answered 19/2, 2015 at 9:11 Comment(0)
I
1

Here's a quick example:

termList = []
termList.append(('term1', [1,2,3,4]))
termList.append(('term2', [5,6,7,8]))
termList.append(('term3', [9,10,11,12]))

result = [x[1] for x in termList if x[0] == 'term3']

print(result)
Institute answered 16/8, 2017 at 23:4 Comment(0)
D
0

With my approach you do not need to import any module, it is more pythonic since it uses python´s native features:

list_of_tuples = [('a1', 'b1','c1'), ('a2', 'b2','c2'), ('a3', 'b3','c3')]

print(list(map(lambda x: x[0], list_of_tuples)))
>> ['a1', 'a2', 'a3']

print(list(map(lambda x: x[2], list_of_tuples)))
>> ['c1', 'c2', 'c3']

By following this logic you can carry out other operations such as getting a particular item from a list of dictionaries, etc.

Doak answered 17/5, 2023 at 1:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.