[Tutor] Question on List Comprehensions

Steve Willoughby steve at alchemy.com
Tue Nov 22 15:54:53 CET 2011

On 21-Nov-11 23:49, Charles Becker wrote:
> Alan, Steve, future readers,
> After some re-reading and hacking I was able to discover the solution.  Since I raised the question here it is :
> [['{0}'.format(x+1), x+1] for x in range(size)]

Just to fill out some other refinements for your information, if you're 
not planning to do anything special with the string formatting in each 
list, you don't really need to call format() when all it's doing is just 
making a string representation of the data value.  so
could just be

Resulting in:
   [[str(x+1), x+1] for x in range(size)]

Also, if you didn't like the repeated x+1 in there, you could just 
change the range call to go from 1..size directly:

   [[str(x), x] for x in range(1,size+1)]

Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C

More information about the Tutor mailing list