[Tutor] Doubt in list comprehension

Mats Wichmann mats at wichmann.us
Fri Feb 23 09:29:20 EST 2018


On 02/23/2018 06:40 AM, Peter Otten wrote:
> vinod bhaskaran wrote:
> 
>> Hi All,
>>
>> I am a beginner programmer and i wrote a small program (as per a
>> assignment i saw) as below:
>>
>> newlist = []
>> for a in range(2,5):
>>   for b in range (0,3):
>>     newlist.append([a])
>>     a = a + 1
>> print(newlist)
>>
>> it gives the expected output as below:
>> [[2], [3], [4], [3], [4], [5], [4], [5], [6]]
>>
>> but when i try list comprehension i am not able to get it correct....can
>> someone please suggest where the (a=a+1) should be placed in a list
>> comprehension
> 
> You canot sneak a statement like
> 
>>     a = a + 1

I would go further: you should not be sneaking it into your original
code either - it's not a great idea to modify the iteration variable
while inside the loop. It works this time because you're iterating over
a list that has been made for you by range:

>>> print(range(2,5))
[2, 3, 4]

so second time through 'a' gets the second value in the list and it
doesn't break things that you changed 'a' while it was in use, but it's
a bad habit to get into - if you use the same concept in a while loop,
say, you will get unpleasant surprises.

So to further Peter's suggestion - try to figure out how to stop doing
that in your inner loop, and it will be much more clear what to do in
the comprehension form.






More information about the Tutor mailing list