I solved the Nested List Python challenge on HackerRank.com passing all test cases. Although this problem can likely be solved with a short script with clever one-liners, my approach was instead to solve it in a clean, understandable way in functional style.
Here is a summary of the challenge, see link above for full description:
Print the name(s) of any student(s) having the second lowest grade; if there are multiple students, order their names alphabetically and print each one on a new line.
The first line contains an integer, \$N\$, the number of students. The \$2N\$ subsequent lines describe each student over \$2\$ lines; the first line contains a student's name, and the second line contains their grade.
I haven't used nested lists much until now and I found myself having to search the internet a good bit for parts of the functions (in particular the
get_lowest_grade function) and I would like to improve this code as much as possible.
def get_students(num_students: int) -> list: """Returns a list of names and grades of N students read from stdin where each name and respective grade is separated by a new line.""" students =  for s in range(0, num_students): name = input() grade = float(input()) students.append([name, grade]) return students def get_lowest_grade(students: list) -> float: """Returns the lowest grade from a list of students[name, grade].""" lowest_grade_student = min(students, key = lambda x: x) return lowest_grade_student def get_lowest_grade_students(students: list) -> list: """Returns the students with the lowest grade from a list of students[name, grade].""" return [s for s in students if s == get_lowest_grade(students)] def exclude_lowest_grade_students(students: list) -> list: """Returns a list of students with the lowest graded students excluded from a list of students[name, grade].""" return [s for s in students if s != get_lowest_grade(students)] def get_student_names_sorted_alpha(students: list) -> list: """Returns a list of names sorted alphabetically from a list of students[name, grade]""" names = [s for s in students] return sorted(names) def main(): num_students = int(input()) students = get_students(num_students) lowest_excluded = exclude_lowest_grade_students(students) second_lowest = get_lowest_grade_students(lowest_excluded) for name in get_student_names_sorted_alpha(second_lowest): print(name) if __name__ == '__main__': main()