[Tutor] Doubt in list comprehension
Peter Otten
__peter__ at web.de
Fri Feb 23 08:40:48 EST 2018
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
into a list comprehension, you have to modify the expressions. Given
[[...] for a in range(2, 5) for b in range(3)]
what expression replacing the ... would give the expected result?
Hint: it depends on both a and b.
Once you have figured it out you can try and reshuffle it a bit into
[[b] for a in range(2, 5) for b in range(...)]
More information about the Tutor
mailing list