Is it possible to delete multiple values in list based on index value in Python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

9th Oct 2019, 4:48 PM
m Jyothi Prasad
m Jyothi Prasad - avatar
5 Answers
+ 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])))
9th Oct 2019, 6:26 PM
rodwynnejones
rodwynnejones - avatar
+ 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]
9th Oct 2019, 7:19 PM
Lothar
Lothar - avatar
+ 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
9th Oct 2019, 5:39 PM
Bilbo Baggins
Bilbo Baggins - avatar
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.
9th Oct 2019, 5:13 PM
rodwynnejones
rodwynnejones - avatar
0
Exploiting the nice idea of compress() from rodwynnejones : https://code.sololearn.com/c0t170OgaCAY/?ref=app
9th Oct 2019, 7:35 PM
Bilbo Baggins
Bilbo Baggins - avatar