Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (Retired) Lists Redux Manipulating Lists

Donald Davis
Donald Davis
10,588 Points

I got a little too brave and tried this. When I ran it through IDLE, it showed me removing str and bool, but not list.

I got a little too brave and tried this. When I ran it through IDLE, it showed me removing str and bool, but not list.

lists.py
the_list = ["a", 2, 3, 1, False, [1, 2, 3]]

# Your code goes below here
the_list.insert(0, the_list.pop(3))

for item in the_list:
    if isinstance(item, str) or isinstance(item, bool) or isinstance(item, list):
        the_list.remove(item)

1 Answer

Hi Donald,

You experienced what could happen when you are iterating over a list and modifying it at the same time.

When you get to the "a" and remove it, everything that comes after it moves down 1 index to take up the missing space.

On the next loop, you should be looking at the 2 but you're looking at the 3 instead since it moved to where the 2 used to be. You've skipped over the 2.

Eventually you get to the boolean value and you remove it. The list then moves down to occupy that space and you skip over it. The for loop ends because there are no more items.

It's recommended that you iterate over a copy of the list while you modify the original list to avoid this type of problem.

You can use slice notation to make a copy of the list like this: the_list[:]

Here's some output from the python shell:

>>> the_list = ["a", 2, 3, 1, False, [1, 2, 3]]
>>> the_list.insert(0, the_list.pop(3))
>>> for item in the_list[:]:
...     if isinstance(item, str) or isinstance(item, bool) or isinstance(item, list):
...             the_list.remove(item)
...
>>> the_list
[1, 2, 3]