Hello I have a list of NamedTuples like this:
from typing import NamedTuple
class Car(NamedTuple):
name: str
mileage: int
lst = [Car(name='car_1', mileage=100), Car(name='car_2', mileage=200)]
How can I remove the corresponding tuple from the list if I just have the car name, say car_1
?
I can create another list by removing, like so:
[namedtup for namedtup in lst if namedtup.name != "car_1"]
but I want to remove it like list remove()
from the original list.
10
I am going to assume you do want to remove it from the original list. But don’t want to recreate it(lst).
# list of Named tuples
lst = [Car(name='car_1', mileage=100), Car(name='car_2', mileage=200)]
# find the matching tuple
car_to_remove = next((car for car in lst if car.name == 'car_1'), None)
# if it exists remove
if car_to_remove:
lst.remove(car_to_remove)
print(lst)
[Car(name='car_2', mileage=200)]
0
If you want to delete a “Car” element by its name, you can create a custom class with modified logic for removing elements.
from typing import NamedTuple
class MyList(list):
def remove(self, a):
for x in self:
if x.name == a:
super().remove(x)
break
class Car(NamedTuple):
name: str
mileage: int
lst = MyList([Car(name="car_1", mileage=100), Car(name="car_2", mileage=200)])
lst.remove("car_1")
print(lst) # [Car(name='car_2', mileage=200)]
1
You can use a list comprehension to find the first car named car_1
in the lst
and remove it using remove()
method:
lst.remove([car for car in lst if car.name == 'car_1'][0])
To avoid iterating over the whole list, you can use next
like this:
lst.remove(next(car for car in lst if car.name == 'car_1', None))
3