0

Is list comprehension in python an imperative program or a declarative program.

For example:

vals = [1,2,3,4,5,6,7,8,9,10]
list2 = [x+2 for x in vals]  # Imperative or Declarative?
print(list2)
Boseong Choi
  • 2,566
  • 9
  • 22

2 Answers2

2

It is a declarative construct borrowed from Haskell, a purely functional programming language.

Python, itself, sticks mostly to an imperative paradigm, although it borrows from functional programming on a case by case basis.

Another way of looking at it, a list-comprehension expresses map/filtering operations (you can of course, abuse it for side effects, but let's stick to its primary use-case, because Python rarely forces you to do things a particular way). Those are both declarative constructs.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
0

If you look the equivalent of this list comprehension

list(map(lambda x: x+2, range(10)))

one ca see that it is basically a declarative statement. However, this is debatable (please see also the comments). You will find arguments for both perspectives.

Michael Dorner
  • 17,587
  • 13
  • 87
  • 117
  • 2
    It is not a for-loop, sure there is one underneath the hood, but you can always do this with anything. "it is still really machine code instructions to modify whatever register, and whatever piece of memory etc etc".The construct is declarative, despite there being an imperative for-loop underneath the hood. Note, it is not a for-loop, – juanpa.arrivillaga May 01 '20 at 07:39
  • You convinced me. :-) I updated my answer accordingly. – Michael Dorner May 01 '20 at 07:49