Trouble with list comprehension
Steve Holden
steve at holdenweb.com
Wed Apr 9 11:50:36 EDT 2008
Shane Lillie wrote:
> I've got a bit of code that looks like this:
>
> for i in xrange(1000):
> # shuffle the doors
> doors = [ 'G', 'C', 'G' ]
> random.shuffle(doors)
>
> # save the doors that have goats (by index)
> 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). I've
> tried changing to a generator as well as using filter() and all 3 give
> the same sort of results. It works if I use a loop, but I'd really
> like to know what I'm doing wrong here. Everything looks like it
> should be working.
>
> Thanks in advance for any suggestions.
Hint: len(range(2)) != 3
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list