[Tutor] Understanding Nested Commands

Ashish Shrestha lists@shrestha.net.np
Wed, 28 Aug 2002 08:25:44 +0545


Alan Colburn wrote:

> One response suggested this:
> 
> 
>>>>myList = [['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 slightly
> stumped in understanding how it works. Can someone take me through what's
> going
> on? 
List comprehension provides ways for mapping a list to another list and
for filtering a list.

     >>> n = range(1,10)
     >>> n
     [1, 2, 3, 4, 5, 6, 7, 8, 9]
     >>> n2 = [i * 2 for i in n]
     >>> n2
     [2, 4, 6, 8, 10, 12, 14, 16, 18]

In the above example, the list n is mapped to another list n2 by
doubling the elements of the first list.


     >>> dogs = ['dogmatix', 'odie', 'snowy', 'snoopy']
     >>> [name.title() for name in dogs]
     ['Dogmatix', 'Odie', 'Snowy', 'Snoopy']
     >>> [len(name) for name in dogs]
     [8, 4, 5, 6]

   Looking at examples, we can see the syntax:

     newlist = [<map function> for <loop variable> in oldlist]

   Filtering works on a similar approach. Elements are added to the
   new list only if it satisfies the filtering condition.

     >>> [name.title() for name in dogs if name[0] == 's']
     ['Snowy', 'Snoopy']
     >>> n = range(1, 10)
     >>> n2 = [i for i in n if i % 2 == 0]
     >>> n2
     [2, 4, 6, 8]

   The syntax for filtering is:


  [<map function> for <loop vairable> in oldlist if <filter function>]


   Using the mapping and filtering the example below shows a method for
   finding a list of prime numbers.

     import math

     def primes(max):
       s = [1,2] + [i for i in range(3, max, 2)]
       for n in range(2, int(math.sqrt(max) + 1)):
         s = [i for i in s if i == n or i % n != 0]
       return s

     print primes(100)


Well, I just love list comprehensions for their compactness. However, 
Tutor has taught me that it is not always the best solutions. It may be 
the easiest but not the most efficient as often the solutions that could 
be programmed to be linear in other cases result in not linear versions 
if we are not careful.

Ashish Shrestha