lint warnings

Gerald Britton gerald.britton at gmail.com
Tue Feb 15 15:03:45 CET 2011


I find:

    map(func, iterable)

to be "neater" than:

    [func(item) for item in iterable]

If nothing else, the "map" version is shorter.  More importantly, in
the 2.x series (which I am often limited to for compatibility
reasons), the variable used in the list comprehension leaks to the
following code:

$ python
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> del item
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'item' is not defined
>>> [int(item) for item in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> item
9
>>>

which can cause hard-to-find bugs.  Fortunately this has been corrected in 3.x.

Also, as already shown, the map version is faster. BTW, if you like:

    [item for item in iterable if predicate(item)]

you can use:

    filter(predicate, item)

I find the latter neater for the same reasons as above

-- 
Gerald Britton



More information about the Python-list mailing list