0
list_d = ["a","b","c",3,5,4,"d","e","f",1,"ee"]
list_e = []

print("Before: %s"%(list_d))
print("Before: %s"%(list_e))

for item in list_d:
    if isinstance(item,int):
        list_d.pop(item)
        list_e.append(item)

print("After: %s"%(list_d))
print("After: %s"%(list_e))

I have this code. I want to transfer those numbers in list_d to list_e, but the result is:

Before: ['a', 'b', 'c', 3, 5, 4, 'd', 'e', 'f', 1, 'ee']
Before: []
After: ['a', 'c', 5, 'd', 'e', 'f', 1, 'ee']
After: [3, 4, 1]

Somehow 5 and 1 is not popping out and 1 is appended to list_e but 5 is not. What's wrong with my code?

Minh Doan
  • 37
  • 7

1 Answers1

5

You're modifying the list as you iterate over it. You could just use list comprehension to make both lists but i'd look into why you have a multi-typed list in the first place

non_ints = [not isinstance(a, int) for a in list_d]
ints = [isinstance(a, int) for a in list_d]

or as a single interation version

non_ints = []
ints = []

for a in list_d:
    if isinstance(a, int):
         ints.append(a)
    else:
         non_ints.append(a)
Sayse
  • 42,633
  • 14
  • 77
  • 146