Home > Back-end >  How to Remove element from the list [duplicate]
How to Remove element from the list [duplicate]

Time:09-23

I want to remove all rohitsharma names from the list remove function is remove only the first one what should I do?

names=['rohitsharma','msd','Brettlee','Dravid','rohitsharma','akhil','python','rohitsharma','dhoni','rohitsharma','rohitsharma']
print(names)
names.remove('rohitsharma')
print(names)

CodePudding user response:

Build from scratch to remove all occurrences:

names[:] = [x for x in names if x != "rohitsharma"]

This is linear (done in a single iteration) while repeated removal is bound by both the length of the list and the number of occurrences. You could also get functional about this one and use filter with the ready-made dunder method:

names[:] = filter("rohitsharma".__ne__, names)

CodePudding user response:

You can use the filter method to check if each element satisfies the condition or not.

names = list(filter(lambda x: x !='rohitsharma', names))
print(names)

Output

['msd', 'Brettlee', 'Dravid', 'akhil', 'python', 'dhoni']
  • Related