List index question

H

Heiko Wundram

questions? said:
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 []:
'3'

What you're trying to do is use a string as an index, which is bound to
fail:
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.
 
Q

questions?

sorry, I realized the problem already. sorry for the confusion.
THanks for the answer!!!
 
M

mrmakent

What you mean to do is y.index('2'), rather than y.index['2']. Call
the index method of the list, rather than try to use index as if it was
itself a list.
 
M

mrmakent

What you mean to do is y.index('2'), rather than y.index['2']. Call
the index method of the list, rather than try to use index as if it was
itself a list.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,274
Messages
2,571,365
Members
48,049
Latest member
robinsonkoff

Latest Threads

Top