Removing from a List in Place

  • Thread starter =?ISO-8859-1?Q?Gregory_Pi=F1ero?=
  • Start date
?

=?ISO-8859-1?Q?Gregory_Pi=F1ero?=

I'm going to assume that it's supposed to work like this, but could
someone tell me the reasoning behind it? I.E. why is 3 skipped?
alist=[1,2,3]
for item in alist:
.... print item
.... if item==2:
.... alist.remove(item)
....
1
2
Bonus Question:
Can we make this behave more intuitiviely in Python 3000?

-Greg
 
J

John Machin

bayerj said:
I'm going to assume that it's supposed to work like this, but could
someone tell me the reasoning behind it? I.E. why is 3 skipped?
Because:
3

You are removing the third item, not the second.

This is incorrect.
You may need to remind yourself that the arg of remove is a value to be
searched for and then removed, not an index. del alist[2] would remove
the third item.

You may have been confused by the OP's obfuscatory example alist = [1,
2, 3].
Consider this equivalent:
| >>> alist = ['foo', 'bar', 'zot']
| >>> for item in alist:
| ... print item
| ... if item == 'bar':
| ... alist.remove(item)
| ...
| foo
| bar
| >>> alist
| ['foo', 'zot']
| >>>

HTH,
John
 
T

Tim Williams

I'm going to assume that it's supposed to work like this, but could
someone tell me the reasoning behind it? I.E. why is 3 skipped?
Because:
3

You are removing the third item, not the second.

Actually, he's removing 2 from the list, but then the length of the
list shrinks by 1 and iteration stops.

The example would have been better if alist = ['a','b','c'] and 'b' was removed.

L.remove(value) -- remove first occurrence of value

you were possibly thinking of alist.pop(2), which removes the item
alist[2] from alist

HTH :)
 

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,433
Messages
2,571,683
Members
48,796
Latest member
Greg L.

Latest Threads

Top