Using an index to get an element, Python

I have a tuple in Python ("A", "B", "C", "D", "E"), how can I find out which element is under a specific index number?

Example: let's say he was given 0, he would return A. If 2, he would return C. If 4, he would return E.

+11
source share
4 answers

What you show, ('A','B','C','D','E')is not list, it is a tuple(parentheses instead of square brackets show this). However, whether you need to index the list or tuple (to get one item in the index), in any case you add the index in square brackets.

So:

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

A ..

( ) , thetuple[0] .. ( ). ( "" ) .

+20
values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.
+3

_ _getitem __ (key).

>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'
+1
x=[2,3,4,5,6,7]
print(x.pop(2)

4

-2

All Articles