PDA

View Full Version : python "remove item from list" question


misterwolfy
10-22-2011, 02:55 PM
I can't figure out why this is wrong. What I want is to end up with just 'k' in the list. Instead I get an out of range error.

What I would expect is that it would count letters, 11 total, then cycle through them printing and removing until only k was left, but maybe the idex changes everytime an item is removed.


letters = ['a','b','c','d','e','f','g','h','i','j','k']
for i in range(10):
print ("this letter is: " + letters[i] )
letters.remove(letters[i])
print letters


Any help? Thanks for reading!

NaughtyNathan
10-22-2011, 03:13 PM
every time you remove an index from that list, the list changes, and therefore indices of all the remaining items changes.

imagine you were doing this:letters.remove(letters[0])that would remove the FIRST item in the list each time, so 'a' would go first time, then 'b' (because b is now the first item), then 'c' (because c is now the first item), etc... right?

now what you are doing is:letters.remove(letters[i])so 'a' goes first, then 'c', then 'e', etc...

get it now? :)

:nathaN

CGTalk Moderation
10-22-2011, 03:13 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.