[Tutor] fancy list things

Karl Pflästerer sigurd at 12move.de
Fri Feb 6 11:42:38 EST 2004


On  6 Feb 2004, Marilyn Davis <- marilyn at deliberate.com wrote:

> I'm sorry, I meant that you can't replace it with a list comprehension
> of any sort?  And zip() can't be replaced with any sort of list
> comprehension.  Right?

maybe I understood you wrong but the example I gave was indeed a list
comp (also a weird one).  So it can be replaced (if you accept some
additional side effects).

zip() can be replaced by a list comp.  That has to be so since we said
before that we can repplace map() with a list comp.  Since zip() can be
written with map() we would have otherwise a contradiction.

zip() written with map():

>>> L = range(5)
>>> M = range(5,10)
>>> N = range(10)
>>> zip(L, M)
[(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]
>>> map(None, L, M)
[(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)]
>>> 

Writing it as a list comp looks not so nice but is possible:

>>> [(L[i], N[i]) for i in min(range(len(L)), range(len(M)))]
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14)]
>>> 

Above resembles the way zip() works:

>>> zip(L,N)
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14)]
>>> 


For the way map() works with lists of different length we have to
rewrite the expression:

>>> map(None, L, N)
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (None, 15), (None, 16), (None, 17), (None, 18), (None, 19)]

>>> def lget (lst, i):
...     try:
...         return lst[i]
...     except IndexError:
...          return
... 
>>> [(lget(L, i), lget(N, i)) for i in max(range(len(L)), range(len(N)))]
[(0, 10), (1, 11), (2, 12), (3, 13), (4, 14), (None, 15), (None, 16), (None, 17), (None, 18), (None, 19)]
>>> 


Above does not mean that anyone with a sane mind would use it in real
code; but it shoes that it is indeed possible to find solutions.

> Is it only useful in map() and filter() and reduce()?  And other
> places where you want to hand a little function to a function?  comp()
> for example.  Is there another class of examples?

Others gave you good examples whre it can be used.

> I'm teaching python for the first time and want to be as solid as
> possible on this stuff.

It's good that you try beforehand to gain as much information as
possible but I'm not sure if lambda should be the first to show to
students in Python.  It can be very useful to write concise, clear and
also nice looking (very important; you have to like the way your code is
written) code but it's not crucial in Python (but others pointed you to
the writings of e.g. David Mertz where he makes heavy use of lambda and
friends in code; there you have an example that it can be extremly
useful).



   Karl
-- 
Please do *not* send copies of replies to me.
I read the list




More information about the Tutor mailing list