There’s little doubt that the remarks below these list comprehensions were made in good faith, but I can’t find any corroboration in docs.python.org
for the assertion that list comprehensions are only meant to be used in a functional programming paradigm.
10: [a_list.pop(len(a_list) - 1 - i) for i,ss in
enumerate(a_list[::-1]) if ss[-1].startswith('X1:')]
20: [a_list.remove(ss) for ss in a_list[::-1] if ss[-1].startswith('X1:')]
Comprehension expressions are functional style.
Do not misuse comprehensions as another way to write afor
loop.
The case seems to be: IF you’re using a functional programming model, then list comprehensions should only produce outputs from the inputs and not modify the inputs.
Does anyone know of a Pythonic Style or best practices guide that says “List comprehensions should only be used for Functional Programming” ? The lines of code above are terse and somewhat obscure, but terse tends to be esoteric and is sometimes an acceptable compromise for compactness. (The lines came from a use case of parsing an esoteric and oddly “structured” dataset, so it’s not surprising that some esoteric code came out of it.)
One of Python’s main features–and strengths–is its willingness to work with statement structures that the programmer comes up with. Many Pythonistas are familiar with the power of prototyping in Python and then porting the algorithm to a faster language. In fact, you can optimize and perfect that prototype so quickly and easily in Python that you might achieve the performance you need fully in Python and not even bother to port it over. Using List Comprehension to mutate that state of an object in-situ appears to be simply a case of Python’s flexibility and ease-of-use.
List comprehensions are reportedly adopted from Haskell [docs.python.org
] (although mathematical set theory is their original source; Haskell’s comprehension uses mathematical set theory notation and syntax). Perhaps the ‘Functional Programming only’ model of list comprehension is simply carrying over from Haskell. Haskell’s slogan, right under the logo on its home page is “An advanced, purely functional programming language”.
[EDIT: ] P.S. Here’s an essay by GvR on Origin of Python’s “Function” Features with an informative quote:
I have never considered Python to be heavily influenced by functional languages, no matter what people say or think.
(P.P.S. This Quora post has a well-written comparison on the difference between Haskell and Python list comprehension.)
The relevant docs I checked:
- Functional Programming HOWTO (a singelton search result. See this Google search.)
- Tutorial Library – Real Python
- Many references on Functional Programming that don’t inherently apply to the context of List Comprehension.