[Tutor] Help understanding list comprehensions

Alan Gauld alan.gauld at btinternet.com
Wed Jun 17 17:22:13 CEST 2015


On 17/06/15 09:58, Anubhav Yadav wrote:

> I understand that my title was a little misleading, and I apologise for the
> same. Here is code that worked:
>
> marks = []
> for i in range(int(input())):

Don't use input(). Use raw_input() instead.
You almost never want input() in python 2.

>      name = raw_input()
>      score = float(raw_input())
>      marks.append([name, score])
> marks = sorted(marks, key=lambda score:score[1])
> lowest = marks[0][1]
> marks = [ x for x in marks if x[1] != lowest]

This creates a brand new list. It eventually overwrites
the original marks list with the new list. But it never
modifies the original marks, it reassigns the new list
to the old variable.


> second_lowest = marks[0][1]
> lowest = sorted([x for x in marks if x[1]==second_lowest])
> for row in lowest:
>      print row[0]
>
> And it worked because I was using list comprehensions for removing the
> element from the list. It didn't worked in the for loop before. I wanted to
> ask why it didn't worked in for loop but worked in list comprehension.

Because the comprehension creates a new list from the old.
You were modifying the original list as you traversed it,
thus breaking your own for loop.

-- 
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