[Tutor] Help understanding list comprehensions

Alan Gauld alan.gauld at btinternet.com
Tue Jun 16 20:17:37 CEST 2015


On 16/06/15 16:45, Anubhav Yadav wrote:
> I have a doubt.

So have I. I can't se your code so I don't know what's happening.
Don't make us guess, show us the code.
>
> I had a list like this
>
> [['Varun', 19.0], ['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0],
> ['Vikas', 21.0]]

But its not assigned to anything?
Or did you really define it by assigning it to a
variable - marks maybe? If so show us the code.

> I am using a for loop to del the rows with the lowest value like this:
>
> for row in marks:
>      if row[1] == lowest:
>          marks.remove(row)

What is 'lowest'? You don;t define it anywhere so you
should get an error. Or maybe you do but you haven't
shown us?

> But after running this loop, I get the following:
>
> [['Kakunami', 19.0], ['Harsh', 20.0], ['Beria', 20.0], ['Vikas', 21.0]]

So it deleted Varun.
I'm guessing but what happened next was that the list counter now 
pointed at index 1, but with Varun gone that is now Harsh, so it
never tests Kakunami. Removing elements from the thing you are iterating 
over is like cutting off the tree branch you are
standing on - a bad idea.

Either take a copy of the list or use a while loop...

> If I print row for every iteration one row is missed in the iteration. Here
> is the output.
>
> ['Varun', 19.0]
> ['Harsh', 20.0]
> ['Beria', 20.0]
> ['Vikas', 21.0]

Which is very odd because its a different set from the previous 'result' 
above. But maybe if you showed us the code we could
understand it.

> If I use list comprehensions, I get the right output. I just want to
> understand what is happening. Can anyone help me out here?

How do you use the list comprehension(s)? Shjow us the code
and we might see why there is a difference. Don't make us guess.


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