Generator comprehension - list None

Jon Ribbens jon+usenet at unequivocal.eu
Tue Oct 18 08:57:03 EDT 2016


On 2016-10-18, Steve D'Aprano <steve+python at pearwood.info> wrote:
> On Tue, 18 Oct 2016 10:43 pm, Sayth Renshaw wrote:
>> I was solving a problem to create a generator comprehension with 'Got '
>> and a number for each in range 10.
>> 
>> This I did however I also get a list of None. I don't understand where
>> none comes from. Can you please clarify?
>
> You get None because print() returns None.
>
> Try this:
>
> result = print("Hello")
> result is None
>
>
> Every time you call print(), it returns None. Normally that just gets thrown
> away, and no harm is done, but when you do it in a generator expression,
> the None values are collected and returned.
>
> Your code:
>
> a = (print("Got {0}".format(num[0])) for num in enumerate(range(10)))
> b = list(a)
> print(b)
>
>
> is equivalent to this:
>
> b = []
> for two_numbers in enumerate(range(10)):
>     num = two_numbers[0]  # pick the first number
>     message = "Got {0}".format(num)
>     result = print(message)
>     b.append(result)
>
> print(b)

I must admit I find the idea of enumerate(range(n)) quite pleasing.
gotta keep track of which numbers those numbers are!



More information about the Python-list mailing list