Hacker News new | ask | show | jobs
by gcr 5656 days ago
This article was written in 2001, and python now includes first-class constructs for many of these.

Map:

  >>> [ord(char) for char in "Hello"]
  [72, 101, 108, 108, 111]
Filter:

  >>> [x for x in xrange(10) if x % 2]
  [1, 3, 5, 7, 9]
For laziness, use parenthesis to turn the above list comprehensions into a generator comprehension. Though I don't demonstrate it, you can work over infinite sequences of objects this way with constant memory usage (without allocating all of them upfront).

  >>> gen = (x for x in range(10) if x % 2)
  >>> gen
  <generator object <genexpr> at 0xb729f6bc>
  >>> for element in gen:
  ...    print element
  ... 
  1
  3
  5
  7
  9

Alice, the rabbit hole begins here --> http://docs.python.org/library/itertools.html
1 comments

The functions are more first-class than list comprehensions and other syntactic alternatives. It's easier, both conceptually and lexically, to mangle, pass around, chain, and combine functions and function argument than it is to write nested list comprehensions.

Not against list comprehensions per se, really. They're just a convenient subset for most commonly idiomatic sequence-mangling-spells, but that's most of what they're good for.