List comprehension
A list comprehension is a syntactic construct available in some programming languages for creating a list based on existing lists. It follows the form of the mathematical '' set-builder notation'' (''set comprehension'') as distinct from the use o ...
is a
syntactic
In linguistics, syntax ( ) is the study of how words and morphemes combine to form larger units such as phrases and sentences. Central concerns of syntax include word order, grammatical relations, hierarchical sentence structure (constituency ...
construct available in some
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s for creating a list based on existing lists. It follows the form of the mathematical ''
set-builder notation
In mathematics and more specifically in set theory, set-builder notation is a notation for specifying a set by a property that characterizes its members.
Specifying sets by member properties is allowed by the axiom schema of specification. Th ...
'' (''set comprehension'') as distinct from the use of
map
A map is a symbolic depiction of interrelationships, commonly spatial, between things within a space. A map may be annotated with text and graphics. Like any graphic, a map may be fixed to paper or other durable media, or may be displayed on ...
and
filter functions.
Examples of list comprehension
Boo
List with all the doubles from 0 to 10 (exclusive)
doubles = *2 for i in range(10)
List with the names of the customers based in
Rio de Janeiro
Rio de Janeiro, or simply Rio, is the capital of the Rio de Janeiro (state), state of Rio de Janeiro. It is the List of cities in Brazil by population, second-most-populous city in Brazil (after São Paulo) and the Largest cities in the America ...
rjCustomers = "RJ"">ustomer.Name for customer in customers if customer.State "RJ"
C#
var ns = from x in Enumerable.Range(0, 100)
where x * x > 3
select x * 2;
The previous code is
syntactic sugar
In computer science, syntactic sugar is syntax within a programming language that is designed to make things easier to read or to express. It makes the language "sweeter" for human use: things can be expressed more clearly, more concisely, or in an ...
for the following code written using lambda expressions:
var ns = Enumerable.Range(0, 100)
.Where(x => x * x > 3)
.Select(x => x * 2);
Ceylon
Filtering numbers divisible by 3:
value divisibleBy3 = ;
// type of divisibleBy3 is Iterable
Multiple "generators":
value triples = ;
// type of triples is Iterable
Clojure
An infinite lazy sequence:
(for (* x x) 3)"> (iterate inc 0)
:when (> (* x x) 3) (* 2 x))
A list comprehension using multiple generators:
(for (+ (* x x) (* y y)) (* z z))"> (range 20)
y (range 20)
z (range 20)
:when ( (+ (* x x) (* y y)) (* z z)) y z
CoffeeScript
largeNumbers = (number for number in list when number > 100)
Common Lisp
List comprehensions can be expressed with the
loop
macro's
collect
keyword. Conditionals are expressed with
if
, as follows:
(loop for x from 0 to 100 if (> (* x x) 3) collect (* 2 x))
Cobra
List the names of customers:
names = for cust in customers get cust.name
List the customers with balances:
names = for cust in customers where cust.balance > 0
List the names of customers with balances:
names = for cust in customers where cust.balance > 0 get cust.name
The general forms:
for VAR in ENUMERABLE here CONDITIONget EXPR
for VAR in ENUMERABLE where CONDITION
Note that by putting the condition and expression ''after'' the variable name and enumerable object, editors and IDEs can provide
autocompletion
Autocomplete, or word completion, is a feature in which an application predicts the rest of a word a user is typing. In Android and iOS smartphones, this is called predictive text. In graphical user interfaces, users can typically press the t ...
on the members of the variable.
Dart
3) i * 2">or (var i in range(0, 100)) if (i * i > 3) i * 2
var pyth = z * z) for (var x in range(1, 20))
for (var y in range(x, 20))
for (var z in range(y, 20)) if (x * x + y * y z * z) ">, y, z"> for (var x in range(1, 20))
for (var y in range(x, 20))
for (var z in range(y, 20)) if (x * x + y * y z * z) [x, y, z
Iterable range(int start, int end) =>
List.generate(end - start, (i) => start + i);
Elixir
for x <- 0..100, x * x > 3, do: x * 2
Erlang
L = lists:seq(0,100).
S = [2*X ">, X <- L, X*X > 3
F#
Lazily-evaluated sequences:
seq
Or, for floating point values
seq
Lists and arrays:
[ for x in 0. .. 100. do if x**2. > 3. then yield 2.*x ]
[, for x in 0. .. 100. do if x**2. > 3. then yield 2.*x , ]
List comprehensions are the part of a greater family of language constructs called computation expressions.
Haskell
x <- x * x > 3"> .. 99 x * x > 3
An example of a list comprehension using multiple generators:
pyth = x <- y <- ..20 y <- z <- [y..20">..20">..20 y <- [x..20 z <- [y..20 x^2 + y^2 z^2">..20 z <- [y..20">..20">..20 y <- [x..20 z <- [y..20 x^2 + y^2 z^2
Io
By using Range object, Io language can create list as easy as in other languages:
Range 0 to(100) asList select(x, x*x>3) map(*2)
ISLISP
List comprehensions can be expressed with the
for
special form. Conditionals are expressed with
if
, as follows:
(for ((x 0 (+ x 1))
(collect ()))
((>= x 100) (reverse collect))
(if (> (* x x) 3)
(setq collect (cons (* x 2) collect))))
Julia
Julia supports comprehensions using the syntax:
y = [x^2+1 for x in 1:10]
and multidimensional comprehensions like:
z = [(x-5)^2+(y-5)^2 for x = 0:10, y = 0:10]
It is also possible to add a condition:
v = 0">x^2 + 2y^2 for x in 1:7 for y in 1:7 if x % y 0
And just changing square brackets to the round one, we get a generator:
g = (3x^2 + 2y^2 for x in 1:7 for y in 1:7 if x % y 0)
Mythryl
s =
3 ">2*i for i in 1..100 where i*i > 3
Multiple generators:
pyth =
z*z ">(x,y,z) for x in 1..20 for y in x..20 for z in y..20 where x*x + y*y z*z
Nemerle
$ x in x*x > 3"> .. 100 x*x > 3
Nim
Nim has built-in seq, set, table and object comprehensions on the sugar standard library module:
import sugar
let variable = collect(newSeq):
for item in @ 9, 1, 42, 0, -1, 9 item + 1
assert variable @ 8, 2, 43, 1, 0, 10
The comprehension is implemented as a macro that is expanded at compile time,
you can see the expanded code using the expandMacro compiler option:
var collectResult = newSeq(Natural(0))
for item in items(@ 9, 1, 42, 0, -1, 9:
add(collectResult, item + 1)
collectResult
The comprehensions can be nested and multi-line:
import sugar
let values = collect(newSeq):
for val in , 2
collect(newSeq):
for val2 in , 4
if (val, val2) != (1, 2):
(val, val2)
assert values @ [(1, 3), (1, 4) @[(2, 3), (2, 4)">[(1,_3),_(1,_4).html" ;"title="[(1, 3), (1, 4)">[(1, 3), (1, 4) @[(2, 3), (2, 4)
OCaml
''OCaml supports List comprehension through OCaml Batteries''.
Perl
my @s = map grep 0..99;
Array with all the doubles from 1 to 9 inclusive:
my @doubles = map 1..9;
Array with the names of the customers based in Rio de Janeiro (from array of hashes):
my @rjCustomers = map @customers;
Filtering numbers divisible by 3:
my @divisibleBy3 = grep 0..100;
PowerShell
$s = ( 0..100 , ? , % )
which is short-hand notation of:
$s = 0..100 , where-object , foreach-object
Python
Python (programming language), Python uses the following syntax to express list comprehensions over finite lists:
S = [2 * x for x in range(100) if x ** 2 > 3]
A generator expression may be used in Python versions >= 2.4 which gives
lazy evaluation
In programming language theory, lazy evaluation, or call-by-need, is an evaluation strategy which delays the evaluation of an Expression (computer science), expression until its value is needed (non-strict evaluation) and which avoids repeated eva ...
over its input, and can be used with
generators to iterate over 'infinite' input such as the count generator function which returns successive integers:
from itertools import count
S = (2 * x for x in count() if x ** 2 > 3)
(Subsequent use of the generator expression will determine when to stop generating values).
R
x <- 0:100
S <- 2 * x 3"> ^ 2 > 3
Racket
(for/list ( 100#:when (> (* x x) 3)) (* x 2))
An example with multiple generators:
(for*/list ( (in-range 1 21) (in-range 1 21) (in-range 1 21) #:when (= (+ (* x x) (* y y)) (* z z)))
(list x y z))
Raku
my @s = ($_ * 2 if $_ ** 2 > 3 for 0 .. 99);
Scala
Using the for-comprehension:
val s = for (x <- 0 to 100; if x*x > 3) yield 2*x
Scheme
List comprehensions are supported in Scheme through the use of the
SRFI-42 library.
Scheme SRFI 42: Eager Comprehensions
/ref>
(list-ec (: x 100) (if (> (* x x) 3)) (* x 2))
An example of a list comprehension using multiple generators:
(list-ec (: x 1 21) (: y x 21) (: z y 21) (if (= (+ (* x x) (* y y)) (* z z))) (list x y z))
SETL
s := ;
Smalltalk
((1 to: 100) select: x squared > 3 collect: x * 2
Visual Prolog
S = [ 2*X , , X = list::getMember_nd(L), X*X > 3 ]
References
{{Reflist
External links
Comparison of list comprehensions on rosettacode.org
*List comprehension
Articles with example C Sharp code
Articles with example Haskell code
Articles with example Lisp (programming language) code
Articles with example Python (programming language) code
Articles with example Racket code
Articles with example Julia code
fr:Compréhension de liste
pt:List comprehension