Python Python Collections Lists Removing items from a list

Andrew Li
Andrew Li
2,222 Points

Great! Now use .remove() and/or del to remove the string, the boolean, and the list from inside of messy_list. When you'

Why doesn't this accept my answer?

for items in messy_list: if type(items) is str: messy_list.remove(items) if type(items) is bool: messy_list.remove(items)

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

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

for items in messy_list:
    if type(items) is str:
        messy_list.remove(items)
    if type(items) is bool:
        messy_list.remove(items)

1 Answer

Steven Parker
Steven Parker
155,473 Points

You're close, but I see two issues:

  • there are other types to be removed besides "str" and "bool"
  • altering a list while using it for iteration can cause the loop to skip items

For the first issue, you might try reversing the test to keep what you want and remove the rest:

    if type(items) is not int:

And for the second, you can iterate using a copy of the list, which can be made with a slice or by using the "copy" method:

for items in messy_list.copy():
Andrew Li
Andrew Li
2,222 Points

Ah! Thats cool! After I posted this question, I realised that there was a type list in there too. Awesome. Thanks for your help. :)

Steven Parker
Steven Parker
155,473 Points

Andrew Li — Glad to help. You can mark the question solved by choosing a "best answer".
And happy coding!