python - Doesn't pop() if a number follows a number -


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

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -