473,238 Members | 1,752 Online

# list.remove() inside for item in aList:

6,596 Expert 4TB
I was chasing a bug last night. I actually saw it before I inserted the trace (print) statements. This:
Expand|Select|Wrap|Line Numbers
1. >>> l=range(10)
2. >>> for i in l:
3. ...     l.remove(i)
4. ...     print i
5. ...
0
2
4
6
8
shows interesting side effects of removing items while looping on a list's items.

However, it works working backwards in the list:
Expand|Select|Wrap|Line Numbers
1. >>> l=range(10)
2. >>> for i in l[::-1]:
3. ...     l.remove(i)
4. ...     print i
5. ...
9
8
7
6
5
4
3
2
1
0
Jun 28 '07 #1
4 1850
ghostdog74
511 Expert 256MB
Expand|Select|Wrap|Line Numbers
1. >>> l=range(10)
2. >>> for i in l[:]:
3. ...  l.remove(i)
4. ...  print i
5. ...
6.
7. 1
8. 2
9. 3
10. 4
11. 5
12. 6
13. 7
14. 8
15. 9
16. >>>
17.
18.
Jun 28 '07 #2
r035198x
13,262 8TB
I was chasing a bug last night. I actually saw it before I inserted the trace (print) statements. This:
Expand|Select|Wrap|Line Numbers
1. >>> l=range(10)
2. >>> for i in l:
3. ...     l.remove(i)
4. ...     print i
5. ...
0
2
4
6
8
shows interesting side effects of removing items while looping on a list's items.

However, it works working backwards in the list:
Expand|Select|Wrap|Line Numbers
1. >>> l=range(10)
2. >>> for i in l[::-1]:
3. ...     l.remove(i)
4. ...     print i
5. ...
9
8
7
6
5
4
3
2
1
0
My explanation is that in l[::-1]: a temporary shallow copy of the list is created and this is where the values of i are read from, but for
Expand|Select|Wrap|Line Numbers
1. >>> for i in l:
The values of i are skiping one each time because after every removal, the elements' positions shift left by one.
Jun 28 '07 #3
bartonc
6,596 Expert 4TB
My explanation is that in l[::-1]: a temporary shallow copy of the list is created and this is where the values of i are read from, but for
Expand|Select|Wrap|Line Numbers
1. >>> for i in l:
The values of i are skiping one each time because after every removal, the elements' positions shift left by one.
Exactly right! That's why ghostdog74's code works going forward. It was 4:20 AM PST when I posted that. By 9:45 that thought had occurred to me, but I was away from the computer.
Jun 28 '07 #4
r035198x
13,262 8TB
Exactly right! That's why ghostdog74's code works going forward. It was 4:20 AM PST when I posted that. By 9:45 that thought had occurred to me, but I was away from the computer.
And i'm still a Python newbie.
Wait till I can give it more time.
Jun 29 '07 #5