Filter a list by marks using python list comprehension

  • In this sample, we will try to filter a list of students based on marks, name or id. List comprehension is a simple way to filter a list in Python. Filter can be applied on single or multi dimensional lists.

    This sample has a list of 5 students. Each item in the list is another list with student id, name and marks. To apply the filter, we can access these values using positional parameters.

    Copied
    from datetime import datetime
    
    #Id, Name, Total Marks
    studentsList = [ [1, 'Carl', 450], [2, 'Tim', 470], [3, 'Peter', 430], [4, 'George', 425], [5, 'Kim', 480] ]
    
    #Filter by marks
    filteredList = [ [ st[0], st[1], st[2] ]  for st in studentsList if st[2] > 450]
    print("Filter based on Marks: " + str(filteredList))
    
    #Filter by id
    filteredList = [ st  for st in studentsList if st[0] < 3]
    print("Filter based on Id: " + str(filteredList))
    
    #Filter by name
    filteredList = [ st  for st in studentsList if ('e' in st[1].lower())]
    print("Filter based on Name: " + str(filteredList))
    
    Output:
      Filter based on Marks: [[2, 'Tim', 470], [5, 'Kim', 480]]
      Filter based on Id: [[1, 'Carl', 450], [2, 'Tim', 470]]
      Filter based on Name: [[3, 'Peter', 430], [4, 'George', 425]]
Absolute Code Works - Python Topics