0
Is it possible to delete multiple values in list based on index value in Python?
Ex: list =[11,52,33,24,51,61,78,82,90,10] Is it possible to delete values in index 1,5,7,9 that is 52,61,82,10
6 Respuestas
+ 3
list_of_indexes = [1, 5, 7, 9]
mylist =[11, 52, 33, 24, 51, 61, 78, 82, 90, 10]
for x in list_of_indexes[::-1]:
del mylist[x]
print('List with items removed', mylist)
# or
mylist2 =[11, 52, 33, 24, 51, 61, 78, 82, 90, 10]
import itertools
print(list(itertools.compress(mylist2, [1, 0, 1, 1, 1, 0, 1, 0, 1, 0])))
+ 3
As already mentioned, there will be an issue if you delete the indexes in the sequence they are named, because index numbers on the right side of delete position change. To get rid of that you can sort index numbers inverse and then use them. So deleting starts at the right side of list, and there is no problem with indexes.
ind_lst = [1,5,7,9]
lst = [11,52,33,24,51,61,78,82,90,10]
for i in sorted(ind_lst, reverse=True):
lst.pop(i)
print(lst)
# output is: [11, 33, 24, 51, 78, 90]
+ 2
Removing 1,5,7,9:
dec = 0
lst.pop(1-dec); dec+=1
lst.pop(5-dec); dec+=1
lst.pop(7-dec); dec+=1
lst.pop(9-dec); dec+=1
0
not in one go, use a loop, but think about what happens when u delete the first item? how can u get round it.
or
lookup itertools compress, 'might' do what u want , not got my IDE to check that though.
0
Exploiting the nice idea of compress() from rodwynnejones :
https://code.sololearn.com/c0t170OgaCAY/?ref=app