4

I think list comprehension is one of the most useful features of Python. I think it would be even more useful if Python allows the recursion inside list comprehension, for something like generation of Fibonacci numbers or prime numbers. I know that Python used to have locals()['_[1]'] for referencing the list that's being generated, but it has never been recommended and had been taken out.

So, is there any reason that Python developers do not want users to use recursion in list comprehension?

ysakamoto
  • 2,512
  • 1
  • 16
  • 22
  • One reason I can think of is that there is no sensible way to extend to unordered collections, like set comprehensions and dict comprehensions. But probably the main reason is that there is not really any use-case where it would be clearer/more readable than using a good old loop. – wim Feb 20 '14 at 17:21

2 Answers2

3

Well, first, you couldn't have infinite list comprehensions, because list comprehensions actually construct real lists. Fitting the Fibonacci sequence into RAM would be tricky.

You might instead ask for a recursive generator expression, because it wouldn't use infinite memory. But we already have generator functions for the use cases that would serve, and generator expressions (like list comprehensions) were designed for simple, common use cases, not to be swiss army knives of data-making.

Sneftel
  • 40,271
  • 12
  • 71
  • 104
  • Your first point is kinda irrelevant. You can also do `[i for i in itertools.count()]` and send cpython into an infinite loop. – wim Feb 20 '14 at 17:28
  • The point is, an unbounded generator makes sense, because you don't have to put it anywhere. An unbounded list comprehension would crash. And the use cases for recursive sequence generation (such as those listed by the OP) tend to be unbounded, so they wouldn't be appropriate for a list comprehension. – Sneftel Feb 20 '14 at 17:35
  • It is not true that the use cases for recursive sequences are unbounded. Many great algorithms are terminating recursive sequences. And the sequences listed by the OP could be trivially turned into bounded versions with a conditional on the comprehension - e.g. generating all fibonacci numbers below 1000. – wim Feb 20 '14 at 17:42
3

I believe this is related to the general guideline that list comprehensions and generator expressions should only be used when they are more simple, clear and clean than the equivalent explicit loop, and this to the point that nested comprehensions, although supported, are generally discouraged from a stylistic point of view.

A recursive comprehension would quickly cross that simplicity threshold.

This also seems to fit the spirit of other, unrelated design decisions, like the lack of a form to declare generalized anonymous functions. You get lambda, which only supports one expression. If you need something more complicated than that, you have to define a regular function.

tawmas
  • 7,443
  • 3
  • 25
  • 24