Python: Find the second lowest grade of any student(s) from the given names and grades of each student using lists and Lambda
Write a Python program to find the second lowest total marks of any student(s) from the given names and marks of each student using lists and lambda. Input the number of students, the names and grades of each student.
Note: If there are multiple students with the same grade then print each name alphabetically.
Sample Solution:
Python Code :
# Initialize empty lists and variables
students = [] # List to store student names and scores
sec_name = [] # List to store names of students with the second lowest grade
second_low = 0 # Variable to hold the second lowest grade
n = int(input("Input number of students: ")) # Accept user input for the number of students
# Iterate 'n' times to get names and scores of students and store them in 'students' list
for _ in range(n):
s_name = input("Name: ") # Accept user input for student name
score = float(input("Grade: ")) # Accept user input for student score
students.append([s_name, score]) # Append student name and score to 'students' list
# Display names and grades of all students entered by the user
print("\nNames and Grades of all students:")
print(students)
# Sort the 'students' list based on grades in ascending order
order = sorted(students, key=lambda x: int(x[1]))
# Find the second lowest grade among the students
for i in range(n):
if order[i][1] != order[0][1]: # Check if the grade is not equal to the lowest grade
second_low = order[i][1] # Set second_low as the second lowest grade found
break
# Display the second lowest grade
print("\nSecond lowest grade: ", second_low)
# Find names of students with the second lowest grade and store them in 'sec_student_name' list
sec_student_name = [x[0] for x in order if x[1] == second_low]
sec_student_name.sort() # Sort the names of students with the second lowest grade
# Display the names of students with the second lowest grade
print("\nNames:")
for s_name in sec_student_name:
print(s_name)
Sample Output:
Input number of students: 5 Name: S ROY Grade: 1 Name: B BOSE Grade: 3 Name: N KAR Grade: 2 Name: C DUTTA Grade: 1 Name: G GHOSH Grade: 1 Names and Grades of all students: [['S ROY', 1.0], ['B BOSE', 3.0], ['N KAR', 2.0], ['C DUTTA', 1.0], ['G GHOSH', 1.0]] Second lowest grade: 2.0 Names: N KAR
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to add two given lists using map and lambda.
Next: Write a Python program to find numbers divisible by nineteen or thirteen from a list of numbers using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics