[Tutor] Understanding Nested Commands

Sean 'Shaleh' Perry shalehperry@attbi.com
Tue, 27 Aug 2002 15:47:05 -0700


On Tuesday 27 August 2002 15:17, Alan Colburn wrote:
>
> One response suggested this:
> >>> myList =3D [['a','b','c'],['d','e','f'],['g','h','i']]
> >>> '\n'.join([','.join(sublist) for sublist in myList])
>
> It's a great solution that does everything I wanted. However, I'm sligh=
tly
> stumped in understanding how it works. Can someone take me through what=
's
> going
> on? Or, alternatively, show me how I might do the exact same thing via
> multiple lines, i.e.,
>

result =3D []
for sublist in myList:
    result.append(','.join(sublist))
'\n'.join(result)

The center work of the code was done by a list comprehension which gives =
you=20
code of the form:

[x for x in list]

a list comprehension's result is a new list much like the functions map()=
 or=20
filter().  In fact I could write the earlier code like this:

'\n'.join(map(lambda x: ','.join(x), myList))

Hope that helps.