0

Hi I have this task in python and I should remove all not int elements, the result of the code down below is [2, 3, 1, [1, 2, 3]] and I have no idea why in the result the list is not moved away. Only tested suggestions please, I mean working ones.

# Great! Now use .remove() and/or del to remove the string, 
# the boolean, and the list from inside of messy_list. 
# When you're done, messy_list should have only integers in it
messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
for ele in messy_list:  
   print('the type of {} is  {} '.format(ele,type(ele)))
   if type(ele) is not int:
     messy_list.remove(ele)
     print(messy_list) 
user3483203
  • 50,081
  • 9
  • 65
  • 94
Joji Ddan
  • 51
  • 4
  • 1
    Do you want the list removed? Or flattened – user3483203 Apr 30 '18 at 15:31
  • 4
    Don't modify the list you're iterating over. – Barmar Apr 30 '18 at 15:32
  • 1
    You're modifying the list while iterating over it. That behaviour is undefined. In particular, in this case, it seems that it removes `False`, therefore moving the list into `False`'s old position, and then finds that the next index is out of bounds for the list. You should create a new list, or really, use a list comprehension. – Mees de Vries Apr 30 '18 at 15:33
  • @MeesdeVries The behaviour is defined and consistent, it's just not intuitive so not recommended – Chris_Rands Apr 30 '18 at 15:40
  • @Chris_rands, my bad, thank you for the correction. – Mees de Vries Apr 30 '18 at 16:03

2 Answers2

3

Try this one:

>>> messy_list = ["a", 2, 3, 1, False, [1, 2, 3]]
>>> [elem for elem in messy_list if type(elem) == int]
[2, 3, 1]
Austin
  • 25,759
  • 4
  • 25
  • 48
2

The issue is not related to the presence of a list inside your messy_list, but rather to the fact you are modifying the list while iterating over it.

For example, with messy_list = ["a", 2, 3, 1, False, "a"] you would get [2, 3, 1, "a"] as a result.

On the other hand: [elem for elem in messy_list if type(elem) == int] returns [2, 3, 1], which is what you want.

byouness
  • 1,746
  • 2
  • 24
  • 41