-2

I am trying to take out numbers from a list that contains both numbers and strings and move them into a new list.

x = 0
list1 = ["a", "b", "c", 1, 2, 3, 4, 5, 6, "d", 7]
list2 = []
for item in list1:
    if isinstance(item, int):
        list2.append(item)
        list1.pop(x)
    x +=  1
list1
list2

The result is not what I expect:

list1
['a', 'b', 'c', 2, 4, 6, 'd']
list2
[1, 3, 5, 7]

I don't understand why the condition is false for the 2nd consecutive numbers from the list, is it because of the way is declared?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    Does this answer your question? [Modifying list while iterating](https://stackoverflow.com/questions/1637807/modifying-list-while-iterating) – Brian61354270 Mar 17 '21 at 18:44
  • 2
    And [another duplicate](https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list-while-iterating-over-it) and [another](https://stackoverflow.com/questions/10539479/how-to-iterate-a-list-while-deleting-items-from-list-using-range-function?noredirect=1&lq=1) and [another](https://stackoverflow.com/questions/6598622/python-removing-items-from-list?noredirect=1&lq=1) – Brian61354270 Mar 17 '21 at 18:45
  • 1
    It is because you are using pop in a for loop. You cannot do this like this. Just create 2 new lists instead. – Justin Oberle Mar 17 '21 at 18:46
  • @Brian sorry, I will try harder next time, I also don't like people who ask right after they have the question At nagyl - Not working, when you remove/pop the item the whole remaining items move "backwards" and at the next iteration you jump over one item. Thank you all, I am surprised to find an answer so fast. – Ștefan Ciobanu Mar 17 '21 at 19:00
  • just do list comprehension, `list2 = [x for x in list1 if isinstance(x, int)] list1 = [x for x in list1 if isinstance(x, str)]` – Shijith Mar 17 '21 at 19:01

2 Answers2

0
list1 = ["a", "b", "c", 1, 2, 3, 4, 5, 6, "d", 7]
list2 = []
list3 = []
for item in list1:
    if isinstance(item, int):
        list2.append(item)
    elif isinstance(item, string):
        list3.append(item)

Instead of using pop to remove indices in a list, just create a new list. When you remove a value from a list you are looping through, the iterations get messed up. Best to not do this.

Justin Oberle
  • 502
  • 3
  • 22
0
list1 = ["a", "b", "c", 1, 2, 3, 4, 5, 6, "d", 7]
integers = []
strings = []

for item in list1:
    if isinstance(item, int):
        integers.append(item)
    elif isinstance(item, str):
        strings.append(item)

but this only works if you know what type of data will be in your list

Jelle
  • 198
  • 9