469,889 Members | 1,241 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,889 developers. It's quick & easy.

Trouble with list comprehension

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.
Apr 9 '08 #1
1 1012
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
Apr 9 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

23 posts views Thread by Fuzzyman | last post: by
35 posts views Thread by Moosebumps | last post: by
6 posts views Thread by jena | last post: by
18 posts views Thread by a | last post: by
4 posts views Thread by Gregory Guthrie | last post: by
4 posts views Thread by bullockbefriending bard | last post: by
1 post views Thread by Waqarahmed | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.