[Tutor] Doubt in list comprehension

vinod bhaskaran bhaskaran.vinod at gmail.com
Fri Feb 23 08:56:15 EST 2018


Thanks Peter.

Shall figure it out with the below hint. I had a hunch am wrong but was not
sure where to put in .

Thanks,
Vinod Bhaskaran

On Fri, Feb 23, 2018, 7:11 PM Peter Otten <__peter__ at web.de> 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
>
> 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(...)]
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list