G
5

A simple trick for getting unstuck with Python loops

I was working on a small project to sort a list of 50 names and kept getting an 'index out of range' error. The problem was I was trying to loop with 'for i in range(len(my_list))' and then remove items inside the loop, which messed up the count. My friend in Austin told me to just build a new list with a list comprehension instead, like 'new_list = [item for item in my_list if condition]'. Has anyone else found a better way to handle filtering lists without errors?
2 comments

Log in to join the discussion

Log In
2 Comments
rivera.christopher
Honestly, why do we always jump to list comprehensions as the only fix? What about using a while loop and going backwards through the list? That way when you remove an item, the indexes you haven't reached yet don't shift around. It's a bit more code but it works right in place without making a new list. Sometimes you need to change the original list and not just make a copy.
9
jason_stone
Check if the list is sorted first, @rivera.christopher.
5