18
votes

I have a tuple in python ('A','B','C','D','E'), how do I get which item is under a particular index number?

Example: Say it was given 0, it would return A. Given 2, it would return C. Given 4, it would return E.

5
Did you try myList[0] and myList[1]? What happened why you tried something? Post the code you tried, please. - S.Lott

5 Answers

28
votes

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

8
votes
values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.
0
votes

You can use _ _getitem__(key) function.

>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'
0
votes

Same as any other language, just pass index number of element that you want to retrieve.

#!/usr/bin/env python
x = [2,3,4,5,6,7]
print(x[5])
-5
votes

You can use pop():

x=[2,3,4,5,6,7]
print(x.pop(2))

output is 4