Find total marks of students using python list comprehension

  • Consider a list of students with marks in multiple subjects. To find the sum of marks, we can use List comprehension.

    Below, there are 2 samples with lists in different formats. First one is a list of id, name and marks in 3 different subjects. To find the sum, we just have to add the marks together.

    Copied
    studentsList = [
        [1, 'Carl', 48, 47, 45 ],
        [2, 'Tim', 43, 42, 41 ],
        [3, 'Peter', 40, 44, 47 ],
        [4, 'George', 44, 49, 50 ],
        [5, 'Kim', 41, 41, 42 ]
    ]
    
    filteredList = [ [ st[0], st[1], st[2]+st[3]+st[4] ]  for st in studentsList]
    print(filteredList)
    
    Output:
    [
    	[1, 'Carl', 140],
    	[2, 'Tim', 126],
    	[3, 'Peter', 131],
    	[4, 'George', 143],
    	[5, 'Kim', 124]
    ]
    
  • If input data is in key-value pairs

    Here, data is listed as key value pairs, with id, name, marks in different subjects and total. We are going to update total in the existing list itself. This is a single line code, if we use List comprehension.

    Otherwise we will have to write a loop to achieve this. Also note that, in order to update some values using List comprehension, we have to use operator library. Call operator.setitem() with 3 parameters, list item, key name and the new value.

    Copied
    import operator
    
    studentsList = [
        {'id': 1, 'name': 'Carl', 'english': 48, 'science': 47, 'maths': 45, 'total': 0 },
        {'id': 2, 'name': 'Tim', 'english': 43, 'science': 42, 'maths': 41, 'total': 0 },
        {'id': 3, 'name': 'Peter', 'english': 40, 'science': 44, 'maths': 47, 'total': 0 },
        {'id': 4, 'name': 'George', 'english': 44, 'science': 49, 'maths': 50, 'total': 0 },
        {'id': 5, 'name': 'Kim', 'english': 41, 'science': 41, 'maths': 42, 'total': 0 }
    ]
    
    [operator.setitem(st, "total", st["english"] + st["science"] + st["maths"]) for st in studentsList]
    
    print(studentsList)
    
    Output:
    [
    	{'id': 1, 'name': 'Carl', 'english': 48, 'science': 47, 'maths': 45, 'total': 140},
    	{'id': 2, 'name': 'Tim', 'english': 43, 'science': 42, 'maths': 41, 'total': 126},
    	{'id': 3, 'name': 'Peter', 'english': 40, 'science': 44, 'maths': 47, 'total': 131},
    	{'id': 4, 'name': 'George', 'english': 44, 'science': 49, 'maths': 50, 'total': 143},
    	{'id': 5, 'name': 'Kim', 'english': 41, 'science': 41, 'maths': 42, 'total': 124}
    ]
    

    If it is required to apply ranking also, refer below link.
    Rank students based on marks

Absolute Code Works - Python Topics