Search code examples
python-2.7objectdel

Removing list object given field value python


Given

This is not simply removing elements from a list; its removing but by using field value

philani = Student(20, "Philani Sithole", "Male", [64,65])
sarah = Student(19, "Sarah Jones", "Female", [82,58])
fabian = Student(50, "Fabian Hamza", "Male", [50,52])


students = [philani, sarah, fabian]

How can I remove the object fabian from students list given the name "Fabian Hamza"

Desired results:

students = [philani, sarah]

It tried this

name = "Fabian Hamza"
for i in xrange(len(students)):
    if hasattr(students[i], name):
        students.pop(i)

But its not working


Solution

  • You can use a list comprehension to achieve that:

    [s for s in students if s.name != 'Fabian Hamza']
    

    If you want just the list of names, try:

    [s.name for s in students if s.name != 'Fabian Hamza']