Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove item from list according to item's special attribute [duplicate]

Tags:

python

list

I have a list composed with my defined items, each of which has a attribute .name

t = [item1, item2]

I want to remove item from the t list according to their attribute .name, like remove() or pop() methods. Maybe I can do something like:

t.remove(item.name=="Removed me")

Maybe I don't need to go through the whole list to filter out the item needed to be removed.

like image 929
Liao Zhuodi Avatar asked Nov 30 '15 10:11

Liao Zhuodi


People also ask

Which is the valid syntax to remove item's from the list?

Using Del statement, we can remove an item from a list using its index.

How do you exclude items from a list in Python?

The remove() method is one of the ways you can remove elements from a list in Python. The remove() method removes an item from a list by its value and not by its index number.

How do you remove all occurrences of an element from a list in Python?

Python3. Method 3 : Using remove() In this method, we iterate through each item in the list, and when we find a match for the item to be removed, we will call remove() function on the list.


1 Answers

List comprehension works well for this kind of stuff

t = [i for i in t if i.name!="Remove me"]

Indeed, as commented, it creates a new list

like image 197
yota Avatar answered Oct 12 '22 21:10

yota