Reputation: 628
I'm currently learning about lists in Python and I have a specific case that I don't really understand.
L=['hello','pie']
L[0][1]
'e'
Why does L[0][1] output as 'e'? I understand that L[0] = 'hello'. So I don't really understand how L[0][1] = 'e'.
Upvotes: 1
Views: 385
Reputation: 7840
A string in python is treated as a sequence of characters for purposes of indexing. Thus the string 'hello'
can be indexed as if it was the list ['h', 'e', 'l', 'l', 'o']
. As the index [1]
refers to the second item in a sequence, you'll get the second letter of the string, 'e'
.
Upvotes: 4
Reputation: 18457
Because you can also index strings in Python.
In [1]: L = ['hello', 'pie']
In [2]: L[0]
Out[2]: 'hello'
In [3]: 'hello'[1]
Out[3]: 'e'
In [4]: L[0][1]
Out[4]: 'e'
Upvotes: 3