Q:

Given a Python list, write a program to remove all occurrences of item 20.

belongs to collection: Python List Exercises

0

Remove all occurrences of a specific item from a list.

Given a Python list, write a program to remove all occurrences of item 20.

Given:

list1 = [5, 20, 15, 20, 25, 50, 20]

Expected output:

[5, 15, 25, 50]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Solution1:Use the list comprehension

list1 = [5, 20, 15, 20, 25, 50, 20]

# list comprehension
# remove specific items and return a new list
def remove_value(sample_list, val):
    return [i for i in sample_list if i != val]

res = remove_value(list1, 20)
print(res)

Solution2:while loop (slow solution)

list1 = [5, 20, 15, 20, 25, 50, 20]

while 20 in list1:
    list1.remove(20)
print(list1)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Initialize dictionary with default values using py... >>
<< You have given a Python list. Write a program to f...