Trouble with list comprehension

Jeffrey Froman jeffrey at fro.man
Wed Apr 9 11:39:12 EDT 2008


Shane Lillie wrote:

> goats = [ x for x in range(2) if doors[x] == 'G' ]
> 
> but for some reason the list comprehension is not always returning a
> list with 2 elements in it (sometimes it will be just 1 element).

The problem here is with your usage of the range() function. You provide an
endpoint of 2, but that endpoint is not included in the range. Thus, you
are only checking the indexes 0 and 1. You'll get two results when those
two indexes are 'G', and one otherwise. You want range(3).

By the way, the enumerate() function is good for this task, as it does not
require you to know the length of your list in advance:

        goats = [index for index, item in enumerate(doors)]

--
Jeffrey



More information about the Python-list mailing list