[Tutor] Help understanding list comprehensions

Alan Gauld alan.gauld at btinternet.com
Wed Jun 17 01:00:55 CEST 2015


On 16/06/15 20:39, Anubhav Yadav wrote:
> I am sorry I didn't posted my code. I had solved this question long 
> back on hackerrank, and I couldn't figure out why this behaviour was 
> seen in this problem, so I had posted this question on their 
> discussion forum. Couldn't get a good answer so I decided to post 
> here. Luckily I found the revision history of my submission there 
> where I could find the earlier code which was giving this error.
>
> Here is the code.
>
> marks = [['Varun', 19.0], ['Kakunami', 19.0], ['Harsh', 20.0], 
> ['Beria', 20.0], ['Vikas', 21.0]]
> marks = sorted(marks, key=lambda score:score[1])
> lowest = marks[0][1]
>
> for row in marks:
>     if row[1] == lowest:
>         marks.remove(row)
>

I already explained why this messes up, don;t mutate the thing
you are iterating over.

> second_lowest = marks[0][1]

This doesn't work because the loop didn't work.

> sh = []
> for row in marks:
>     if second_lowest == row[1]:
>         sh.append(row)
>

This could be a comprehension if you wanted

sh = [ row for row in marks if second_lowest == row[1] ]

But you haven't shown where you printed the 'output' that
was wrong, nor have you shown the comprehensions which
'worked'.

As it is you need to fix the first for loop before anything
else can work as you want it to.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list