Does EK9 have list comprehensions like Python?
← What AI Gets Wrong About EK9 · Ref: Q1066
No. EK9 has NO list comprehensions. This syntax does not exist:
[x*2 for x in items if x > 0] [x for x in items when x > 0]
These are Python syntax. EK9 does not have them.
Use a stream pipeline instead:
results <- cat items | filter by isPositive | map with doubleIt | collect as List of Integer
The stream pipeline is more powerful than list comprehensions:
- Named functions make the intent clear
- Pipeline stages can be reordered easily
- head, tail, sort, group, flatten are available
- The result type is explicit
Define the helper functions:
isPositive() as pure -> item as Integer <- rtn as Boolean: item > 0
doubleIt() as pure -> item as Integer <- rtn as Integer: item * 2
See Q1061 for reusable filter functions. See Q1062 for transform functions. See Q1063 for a complete program.
Example
defines module qa.aimistakes.nolistcomprehensions defines function isPositive() as pure -> item as Integer <- rtn as Boolean: item > 0 doubleIt() as pure -> item as Integer <- rtn as Integer: item * 2 defines program NoComprehensionDemo() stdout <- Stdout() items <- [-3, 5, -1, 8, 0, 12, -7, 3] //Stream pipeline replaces list comprehension results <- cat items | filter by isPositive | map with doubleIt | collect as List of Integer stdout.println(`Doubled positives: ${results}`)
Common mistakes
E01081 — EK9 has no list comprehension syntax. Use a stream pipeline: cat source | filter by fn | map with fn | collect as Type.
Incorrect:
results <- [x*2 for x in items if x > 0]
Correct:
results <- cat items | filter by isPositive | map with doubleIt | collect as List of Integer
Other ways to ask this
- Can I write [x*2 for x in items] in EK9?
- Is there a list comprehension syntax in EK9?
- How do I create a filtered list in one line in EK9?
Coming from another language?
Python: [x*2 for x in items if x > 0]. EK9: cat items | filter by pred | map with fn | collect as Type. No list comprehensions exist in EK9.
Keywords: python, stream, mistake, comprehension, list, pipeline