0

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

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

3 Comments

@user3501595, Alternatively, you can do: for i in mylist: and then print i,mylist[i]
@sshashank124 do you mean for i in range(0,len(mylist)): ?
Since we have enumerate, there are few reasons (well, good reasons I mean) to use for i in range(len(mylist)):. The above use case is definitly not one of them.
0

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

3 Comments

so what will be the result is i give mylist[i] ..is it possible in python ?...can you tell me its use ?
@user3501595 : this is fully documented, you know. cf docs.python.org/2/tutorial/introduction.html#lists and docs.python.org/2/reference/… for a start.
thanks ..and can you tell me in which situation do i wanna add mylist[i] = mylist[i]+1...Please ..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.