[Tutor] Stuck on Error
Steven D'Aprano
steve at pearwood.info
Mon Dec 23 00:47:26 CET 2013
On Sun, Dec 22, 2013 at 04:39:24AM -0500, Keith Winston wrote:
[...]
> You could do this entire piece with a list comprehension in one line, but
> I'm only mentioning it b/c I just learned them. My crude first effort would
> look like this:
>
> RN = [] # create the array RN
> [RN.append(random.randint(1, 75)) for i in range(5)] # populate the array
Definitely a crude first effort :-)
I'm afraid you've missed the point of list comprehensions if you write
them like that. Here is how you should write the above: just call the
function you want to append with directly, no need for an extra append.
RN = [random.randint(1, 75)) for i in range(5)]
The list comprehension itself creates a new list and populates it. No
need to pre-create an empty list and then populate it.
What your code ends up doing is:
- create an empty list, RN
- run a list comprehension which builds a temporary
list [None, None, None, None, None]
- as a side-effect of building that temp list, populate
the RN list
- throw away the temp list
The end result probably does twice as much work as needed.
In your list comp, you call RN.append(something) five times. Each call
to RN.append returns None. That's not obvious from the interactive
interpreter, because it suppresses printing of None as a convenience,
but it is true:
py> result = [].append(23)
py> print(result)
None
So your list comp builds a list made up of nothing but None, only to
throw it away immediately it is done.
--
Steven
More information about the Tutor
mailing list