'What is the purpose of [marks for name, marks in marksheet]

Here is the code

marksheet = []

for _ in range(0,int(input())):

    marksheet.append([input(), float(input())])

second_highest = sorted(list(set([marks for name, marks in marksheet])))[1]

print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))

Doesn't the [marks for name, marks in marksheet] produce the same list as marksheet? So couldn't we get the same result with second_highest = sorted(list(set(marksheet)))[1] ?



Solution 1:[1]

Here, I would add a small contribution intended for all new coders with no experience.

The line [marks for name, marks in marksheet] needs to be read as

-> marks----for----name, marks----in----marksheet

Initially, I too was confused as I was reading it as

-> marks for name,----marks in marksheet

However silly this may sound, I have to admit that I faced this problem. After staring at the simple line for a while, it just came to me and I shifted my perspective. If this answer could help anyone, I am grateful.

Solution 2:[2]

As mentioned by chepner, marksheet is a list of list (2 items inside inner list).

For a input of 2, marksheet would be

marksheet = [['Mark' , 1.2 ], ['Sam', 2.0]]

Now, this list comprehension --> [marks for name, marks in marksheet] takes each list item in the marksheet list, and then just takes out the marks from each element.

so, the output would be a new list --> [1.2, 2.0] which is different from the original marksheet list.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Khoka07
Solution 2 gsb22