Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Introducing Lists Using Lists Mutability

Akanksha Singh
Akanksha Singh
5,083 Points

Why doesn't list.remove() removes all the elements after using a for in loop, but using loop in for list.copy() does?

#code for review - aim to remove all the elements from the list
l = [1,2,3,4,5,6]

#removed one element
l.remove(2)
#looping through list and removing element
for num in l:
     l.remove(num)
#expected an empty list but instead got two items that too not the last two
print (l)

#if I use l.copy() in the loop then it works
for num in l.copy():
     l.remove(num)
#got an empty list
print(l)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Modifying the loop iterable shifts the items relative to their indexes:

#code for review - aim to remove all the elements from the list
l = [1,2,3,4,5,6]

#removed one element
l.remove(2)
#looping through list and removing element
for idx, num in enumerate(l):
     l.remove(num)
     print('loop 1:', l, idx, num)
#expected an empty list but instead got two items that too not the last two
print ('result 1:', l)

l = [1,2,3,4,5,6]

#if I use l.copy() in the loop then it works
for idx, num in enumerate(l.copy()):
     l.remove(num)
     print('loop 2:', l, idx, num)
#got an empty list
print('result 2:', l)

Produces

loop 1: [3, 4, 5, 6] 0 1
loop 1: [3, 5, 6] 1 4
loop 1: [3, 5] 2 6
result 1: [3, 5]
loop 2: [2, 3, 4, 5, 6] 0 1
loop 2: [3, 4, 5, 6] 1 2
loop 2: [4, 5, 6] 2 3
loop 2: [5, 6] 3 4
loop 2: [6] 4 5
loop 2: [] 5 6
result 2: []
Prateek Sharan Lall
Prateek Sharan Lall
1,778 Points

After half an hour of this, I understood it.

Basically, how the for loop is working is first taking the index, say '0', then assigning it to the variable we chose. e.g., in Chris's awesome reply above, python first takes idx as 0, then assigns the value at 0th position to num, which is '1' and removes it. The second time, idx is set to 1, and assigns the second element in the list (second will be like 0, then 1). and the second position of the modified list is not '3' anymore. It is '4', which removes it. Computers can be smart, but sometimes! :D

Chris's example above is great and helped me understand this concept and also I learnt the enumerate() function! Thanks a lot Chris! :) ta