python - Doesn't pop() if a number follows a number -
this question has answer here:
- strange result when removing item list [duplicate] 4 answers
- remove items list while iterating 18 answers
that code should clear list 'bag' out of numbers. number follows number doesn't work right. example 8 after 7.
bag = ['apples', 1,'bananas', 'potatoes', 'tomatoes',2, 'chary',3, 'mo4ka', 7,8, 'candies', 'main_tx'] list_n = [] x = 0 in bag: if isinstance(i, int): list_n.append(i) bag.pop(x) x+=1 print(list_n) print(bag)
result:
[1, 2, 3, 7] ['apples', 'bananas', 'potatoes', 'tomatoes', 'chary', 'mo4ka', 8, 'candies', 'main_tx']
don't try modify list while iterating on it.
list_n = [] new_bag = [] x in bag: # which_list = list_n if isinstance(x, int) else new_bag # which_list.append(x) if isinstance(x, int): list_n.append(x) else: new_bag.append(x) bag = new_bag
Comments
Post a Comment