Code 1:
%%timeit
students = [['Zack',38],['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
second_highest = sorted(list(set([x[1] for x in students])))[1]
([a for a,b in sorted(students) if b == second_highest])
Code 2:
%%timeit
students = [['Zack',38],['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]]
s = sorted(set([x[1] for x in students]))
for name in sorted(x[0] for x in students if x[1] == s[1]):
name
Now I am confused about execution of two programs, how is code2 is faster than code code1, despite use of nested for loop in code2. Image below is from Jupyter notebook which show mean time taken by code from 100000 loops. Although the difference is very minute but I am confused because how can nested for-loop work faster than single for loop.
I was supposed to Print the output, so can put print before the last line of code