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
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)
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 ]
© 2024 OneMinuteCode. All rights reserved.