ValueError when removing Python list: list.remove(x): x not in list

Asked 2 years ago, Updated 2 years ago, 19 views

car = ['BMW', 'BENZ', 'VOLKSWAGEN', 'AUDI','BMW','BMW', 'BENZ', 'VOLKSWAGEN', 'AUDI','BMW','BMW']
for i in car:
    car.remove('BMW')

It says value error. Why is that? I need to erase only BMW using the for door, what should I do?

python

2022-09-20 15:54

2 Answers

You do not need to use the for statement when you use the remove command in the list. If you want to use the for statement, you should use it as follows:

car = ['BMW', 'BENZ', 'VOLKSWAGEN', 'AUDI','BMW','BMW', 'BENZ', 'VOLKSWAGEN', 'AUDI','BMW','BMW']
for i in car:
    if i == 'BMW':
        car.remove(i)


2022-09-20 15:54

Beginner's answer may not be completely removed.

>>> car
['BMW', 'BMW', 'BMW', 'BMW', 'BMW', 'BMW', 'BMW']
>>> for i in car:
    if i == "BMW":
        car.remove(i)


>>> car
['BMW', 'BMW', 'BMW']

Instead, you can do it like this.

>>> for _ in range(car.count("BMW")):
    car.remove()

If I were to do list comprehension, like this.

car = [ e if e != "BMW" for e in car ]


2022-09-20 15:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.