List index question

Heiko Wundram modelnine at bit-bukket.org
Wed Dec 7 15:46:42 EST 2005


questions? wrote:
> I want to do list index function.
>>>> y=['1','2','3','4']
>>>> y
> ['1', '2', '3', '4']
>>>> y.index['2']
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: unsubscriptable object
> 
> It works with y=[1,2,3,4].  Anyone has any hint, what's the reason
> here?

You're mixing things up badly. Either you want to call the function .index()
of the list object, in which case you don't use angle brackets but rather
round brackets (which works):

>>> y = ['1','2','3','4']
>>> y.index('2')
1

or you want to get an element at a specified position in the list, in which
case you don't use .index() but rather index the object using []:

>>> y = ['1','2','3','4']
>>> y[2]
'3'

What you're trying to do is use a string as an index, which is bound to
fail:

>>> y['2']
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: list indices must be integers

And the error message says it all: a list index must be an integer.

I guess you better do some reading up on Python syntax... Have you done the
tutorial?

--- Heiko.



More information about the Python-list mailing list