user3501595
user3501595

Reputation: 13

Index confusion in python

Hello folks am new to python development.I have wrote a sample code:

mylist = ['something','baby','car']
for i,n in mylist:
    mylist[i] = mylist[i]+1
    print i,n

I know i is the index in the list so it will execute up to the number of elements in the list.But when I execute the script I get type error...

In this code the index of the list is inceremented by one... So the expected result is.

0 something
1 baby
2 car

Instead of that i got a typeerror..Please help me in solving this..Any help would be appreciated..Thanks

Upvotes: 0

Views: 80

Answers (2)

bruno desthuilliers
bruno desthuilliers

Reputation: 77902

This :

mylist = ['something','baby','car']
for i,n in mylist:
    mylist[i] = mylist[i]+1
    print i,n

raises a ValueError ("Too many values to unpack") on the second line.

If you just add enumate on this second line, ie for i,n in enumerate(mylist):, then you get a TypeError on the next line, because you are trying to add a string (mylist[i]) and an integer (i). The point is: what you want to increment is i, not mylist[i] (which is the same thing as n fwiw), so it should be:

for i, n in enumerate(mylist):
    i = i + 1
    print i, n

BUT you don't have to go thru such complications to print out "index+1 : item at index+1", all you need is to pass the optional start argument to enumerate:

mylist = ['something','baby','car']
for i, n in enumerate(mylist, 1):
    print i, n

Upvotes: 0

C.B.
C.B.

Reputation: 8326

Very close, just missing enumerate--

for i,n in enumerate(mylist):

However, the code above will attempt to add an integer to a string; this will throw a new error. If you are trying to push elements back, you would want mylist[i] = mylist[i+1] (note you would have to have a case to catch the last element)

Upvotes: 3

Related Questions