Python: Nested List Comprehensions

Using nested list comprehensions to find second lowest score(s)

nick3499
1 min readSep 15, 2017

n = int(input()) becomes the first value of 5 entered above, which indicates how many students, along with their total scores, are listed.

nlist = [[input(), float(input())] for _ in range(n)] iterates through students/points items entered. [input(), float(input())] sets the format of each nested list, e.g. ['Harry', 37.21]. nlist stores the nested lists: [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41.0], ['Harsh', 39.0]].

second_lowest = sorted(list(set([marks for name, marks in nlist])))[1] gets the second lowest score. The set() function removes the extra 37.21 value so that the second lowest value can be indexed, e.g. [1].

Finally, '\n'.join([a for a, b in sorted(nlist) if b == second_lowest]) is for iterating through the identical second lowest scores, sorting them, and printing them line by line, similar to format.

After executing the script, entered the data manually as shown below:

$ python nested_list_comprehensions.py
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

The script will print the students with second lowest scores:

Berry
Harry

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet