billyandriam
billyandriam

Reputation: 130

Popping all of the elements of a list

I'm learning the basics of Python and with a forloop, I am trying to use the pop method in order to remove all of the elements of my list. To my surprise anyway, some elements remain and I don't know why.

thelist = ['CompSci', 'Math', 'Chemistry', 'Art', 'Physics', 'Sports', 'Economics', 'Biology']


for items in thelist:
    thelist.pop(0)

print(thelist)

I expect to end up with an empty set, but the actual output is the last 4 elements ['Physics', 'Sports', 'Economics', 'Biology'].

Upvotes: 2

Views: 57

Answers (3)

watercoderbrick
watercoderbrick

Reputation: 16

I fully agree with Ron Serruya's answer and I've got a very similar example, only printing the list twice for extra clarity.

A rule of thumb that can be applied is to never try to drop items from any iterator. This can be difficult to debug in my opinion.

thelist = ['CompSci', 'Math', 'Chemistry', 'Art', 'Physics', 'Sports', 'Economics', 'Biology']

for items in thelist:
    print(items)
    print(thelist)
    thelist.pop(0)
    print(thelist)

Upvotes: 0

Stanislav Lipovenko
Stanislav Lipovenko

Reputation: 574

That's because list is mutable object. You just can't remove items while iterating through it and get the result you expect. Use this:

list_len = len(thelist)
for _ in range(list_len):
    thelist.pop(0)

Upvotes: 0

Ron Serruya
Ron Serruya

Reputation: 4426

Let's print the item and list while iterating

In [5]: thelist = ['CompSci', 'Math', 'Chemistry', 'Art', 'Physics', 'Sports', 'Economics', 'Biology'] 
   ...:  
   ...:  
   ...: for items in thelist: 
   ...:     print(items) 
   ...:     thelist.pop(0) 
   ...:     print(thelist) 
   ...:  
   ...:                                                                                                                                                                      
CompSci
['Math', 'Chemistry', 'Art', 'Physics', 'Sports', 'Economics', 'Biology']
Chemistry
['Chemistry', 'Art', 'Physics', 'Sports', 'Economics', 'Biology']
Physics
['Art', 'Physics', 'Sports', 'Economics', 'Biology']
Economics
['Physics', 'Sports', 'Economics', 'Biology']

So every time the loop runs you go one item forward, and also remove one item from the list, so you iterate the list 4 times instead of 8

Upvotes: 2

Related Questions