Comparison of programming languages (list comprehension)

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 of map and filter functions.

Examples of list comprehension

Boo

List with all the doubles from 0 to 10 (exclusive)

doubles = [i*2 for i in range(10)]

List with the names of the customers based in Rio de Janeiro

rjCustomers = [customer.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 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 = { for (i in 0..100) if (i%3==0) i };
// type of divisibleBy3 is Iterable<Integer>

Multiple "generators":

value triples = { for (x in 0..20) for (y in x..20) for (z in y..20) if (x*x + y*y == z*z) [x,y,z] };
// type of triples is Iterable<Integer[3]>

Clojure

An infinite lazy sequence:

 (for [x (iterate inc 0) 
       :when (> (* x x) 3)]
   (* 2 x))

A list comprehension using multiple generators:

 (for [x (range 20)
       y (range 20)
       z (range 20)
       :when (== (+ (* x x) (* y y)) (* z z))]
   [x 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 [where CONDITION] get 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 on the members of the variable.

Dart

[for (var i in range(0, 100)) if (i * i > 3) i * 2]
var pyth = [
  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<int> 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 { for x in 0 .. 100 do if x*x > 3 then yield 2*x }

Or, for floating point values

seq { for x in 0. .. 100. do if x**2. > 3. then yield 2.*x }

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 * 2 | x <- [0 .. 99], x * x > 3]

An example of a list comprehension using multiple generators:

pyth = [(x,y,z) | x <- [1..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 = [3x^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 = [ 2*i for i in 1..100 where i*i > 3 ];

Multiple generators:

 pyth = [ (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*2 | x in [0 .. 100], x*x > 3]

Nim

Nim has built-in seq, set, table and object comprehensions on the sugar standard library module:[1]

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 [1, 2]:
    collect(newSeq):
      for val2 in [3, 4]:
        if (val, val2) != (1, 2):
          (val, val2)
        
assert values == @[@[(1, 3), (1, 4)], @[(2, 3), (2, 4)]]

OCaml

OCaml supports List comprehension through OCaml Batteries.[2]

Perl

my @s = map {2 * $_} grep {$_ ** 2 > 3} 0..99;

Array with all the doubles from 1 to 9 inclusive:

my @doubles = map {$_ * 2} 1..9;

Array with the names of the customers based in Rio de Janeiro (from array of hashes):

my @rjCustomers = map {$_->{state} eq "RJ" ? $_->{name} : ()} @customers;

Filtering numbers divisible by 3:

my @divisibleBy3 = grep {$_ % 3 == 0} 0..100;

PowerShell

$s = ( 0..100 | ? {$_*$_ -gt 3} | % {2*$_} )

which is short-hand notation of:

$s = 0..100 | where-object {$_*$_ -gt 3} | foreach-object {2*$_}

Python

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 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[x ^ 2 > 3]

Racket

(for/list ([x 100] #:when (> (* x x) 3)) (* x 2))

An example with multiple generators:

(for*/list ([x (in-range 1 21)] [y (in-range 1 21)] [z (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.[3]

(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 := {2*x : x in {0..100} | x**2 > 3 };

Smalltalk

((1 to: 100) select: [ :x | x squared > 3 ]) collect: [ :x | x * 2 ]

Visual Prolog

S = [ 2*X || X = list::getMember_nd(L), X*X > 3 ]

References

Read other articles:

Peta Austria-Hungaria setelah perang dunia I Pembubaran Austria-Hungaria adalah peristiwa geopolitik besar yang terjadi sebagai akibat dari tumbuhnya kontradiksi sosial internal dan pemisahan berbagai bagian Austria-Hungaria. Alasan runtuhnya negara adalah Perang Dunia I, gagal panen tahun 1918 dan krisis ekonomi. Revolusi Oktober dan pengumuman dari Januari 1918 dan seterusnya mendorong sosialisme di satu sisi, dan nasionalisme di sisi lain, atau sebagai alternatif kombinasi dari kedua kecen...

Casper Nielsen[1]​ Nielsen en 2016Datos personalesNacimiento Esbjerg, Dinamarca29 de abril de 1994 (29 años)Nacionalidad(es) DanesaAltura 1,79 m (5′ 10″)Carrera deportivaDeporte FútbolClub profesionalDebut deportivo 2013(Esbjerg fB)Club Club BrujasLiga Primera División de BélgicaPosición CentrocampistaDorsal(es) 27Goles en clubes 39Trayectoria Esbjerg fB (2013-2017) Odense BK (2017-2019) Union Saint-Gilloise (2019-2022) Club Brujas (2022-presente)[editar datos en Wiki...

Dieser Artikel oder nachfolgende Abschnitt ist nicht hinreichend mit Belegen (beispielsweise Einzelnachweisen) ausgestattet. Angaben ohne ausreichenden Beleg könnten demnächst entfernt werden. Bitte hilf Wikipedia, indem du die Angaben recherchierst und gute Belege einfügst. Steve Englehart, San Diego Comic Convention Steve Englehart (* 22. April 1947 in Indianapolis) (Pseudonyme: John Harkness, Cliff Garnett) ist ein US-amerikanischer Comicautor. Inhaltsverzeichnis 1 Leben 2 Sammelbände ...

Para otros usos de este término, véase El Periódico. elPeriódicoTipo Informativo, político, de opinión e investigativoFormato Tabloide (11” x 13”)País Guatemala GuatemalaSede Ciudad de GuatemalaÁmbito de distribución GeneralFundación 6 de noviembre de 1996Fundador(a) José Rubén Zamora MarroquínFin de publicación 15 de mayo de 2023Ideología política CentroizquierdaIdioma EspañolPrecio Q. 3.00Frecuencia DiarioTirada 30 000 Aprox.Difusión NacionalCirculación Naci...

بابنيان   معلومات شخصية الميلاد مارس 142  حمص[1][2][3]  الوفاة سنة 211 (68–69 سنة)  روما  سبب الوفاة قطع الرأس  مواطنة روما القديمة  الحياة العملية المهنة محاماة[5][6]  اللغات اللاتينية  مجال العمل قانون  الخدمة العسكرية الولاء الإمبراطو

جزء من سلسلة حول تاريخ اليمن  تاريخ اليمن القديم  مملكة سبأ مملكة حضرموت مملكة أوسان مملكة كندة مملكة قتبان مملكة معين مملكة حمير 110 ق.م - 527 م اليمن الأكسومي 527 - 575 م اليمن الساساني 575 - 628 م  تاريخ اليمن الإسلامي العصر النبوي 610 - 632 الخلافة الراشدة 632 - 661 العصر الأموي 661 - 750

1979 studio album by Bonnie TylerDiamond CutStudio album by Bonnie TylerReleasedFebruary 1979Recorded1978StudioRAK Studios, LondonGenreCountry, pop rock[1]Length35:01LabelRCAProducer Robin Geoffrey Cable Ronnie Scott Steve Wolfe Bonnie Tyler chronology Natural Force(1978) Diamond Cut(1979) Goodbye to the Island(1981) Singles from Diamond Cut My Guns Are LoadedReleased: November 1978 Louisiana RainReleased: December 1978 What a Way to Treat My HeartReleased: March 1979 Too Good...

هذه المقالة تحتاج للمزيد من الوصلات للمقالات الأخرى للمساعدة في ترابط مقالات الموسوعة. فضلًا ساعد في تحسين هذه المقالة بإضافة وصلات إلى المقالات المتعلقة بها الموجودة في النص الحالي. (يوليو 2023) ميرسيدس بينز إي كلاسمعلومات عامةالعلامة التجارية مرسيدس-بنز المصنع دايملرالإ�...

George GrayBornGeorge William Gray4 September 1926Died12 May 2013 (aged 86)OccupationProfessor of Organic ChemistrySpouse Marjorie Canavan ​ ​(m. 1953⁠–⁠2013)​ George William Gray CBE FRS (4 September 1926 – 12 May 2013) was a Professor of Organic Chemistry at the University of Hull who was instrumental in developing the long-lasting materials which made liquid crystal displays possible. He created and systematically developed liqui...

Істанбул Парк Розташування Стамбул, ТуреччинаЧасовий пояс UTC+2Координати 40°57′06″ пн. ш. 29°24′18″ сх. д. / 40.95167° пн. ш. 29.40500° сх. д. / 40.95167; 29.40500Відкрито 21 серпня 2005Головні події F1, GP2, MotoGP, DTM, WTCCВебсайт intercitypark.comДовжина 5,338 кмПовороти 14Рекорд 1:24.5...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Indonesian Institute of the Arts, Surakarta – news · newspapers · books · scholar · JSTOR (May 2017) (Learn how and when to remove this template message)Indonesia Institute of the Art SurakartaJavanese: ꦆꦤ꧀ꦱ꧀ꦠꦶꦠꦸꦠ꧀​ꦱꦼꦤꦶ​ꦆꦤ�...

This article is about the 6mm caliber Lee rifle. For other uses, see Lee rifle. Bolt-action rifle Lee Rifle, Model of 1895, Caliber 6mm Lee Navy rifle M1895, open boltTypeBolt-action riflePlace of originUnited StatesService historyIn service1895–1907Used byUnited States Navy United States Marine CorpsWarsSpanish–American WarPhilippine–American WarBoxer RebellionProduction historyDesignerJames Paris LeeManufacturerWinchester Repeating Arms CompanyProduced1895No. ...

Skyscraper in Kuala Lumpur, Malaysia KH TowerMalay: Menara KHThe KH Tower in 2018General informationTypeOfficesLocationJalan Sultan Ismail, Kuala Lumpur, MalaysiaCompleted1983HeightRoof152 m (499 ft)Technical detailsFloor count36 KH Tower (Malay: Menara KH, formerly known as Promet Tower) is a 36-storey, 152 m (499 ft) tall skyscraper in Kuala Lumpur, Malaysia. Between 1983 and 1984, it was the tallest building in Malaysia, the second to surpass the height of 150 m (4...

  提示:此条目的主题不是鄧鏡波學校。 本條目存在以下問題,請協助改善本條目或在討論頁針對議題發表看法。 此條目需要补充更多来源。 (2020年7月27日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能會因為异议提出而被移除。致使用者:请搜索一下条目的标题(来源搜索:香港鄧鏡波書院 — 网页、新闻、书籍、学术、图像),以检查网络�...

American professional wrestler Ranger RossBirth nameRobert Lee Ross Jr.Born (1959-07-15) July 15, 1959 (age 64)Acworth, Georgia, United StatesProfessional wrestling careerRing name(s)The PearlRanger RossBilled height5 ft 10 in (178 cm)}Billed weight235 lb (107 kg)Billed fromAcworth, GeorgiaTrained byTed AllenDebut1986Retired2007Military serviceAllegiance United StatesService/branch United States ArmyUnit75th Ranger RegimentBattles/warsOperation Urgent Fury R...

Municipality in Oriental, MoroccoKassita KasitaكاسيطاmunicipalityLocation of kassita in Driouch ProvinceCoordinates: 34°53′24″N 3°43′41″W / 34.890°N 3.728°W / 34.890; -3.728Country MoroccoRegionOrientalProvinceDriouch ProvincePopulation (2014) • Total2,675Time zoneUTC+0 (WET) • Summer (DST)UTC+1 (WEST) Kassita (Tarifit: Kasita, ⴽⴰⵙⵉⵜⴰ; Arabic: كاسيطا) is a small town in the Driouch Province in northe...

American electrical engineer Elisha GrayBorn(1835-08-02)August 2, 1835Barnesville, Ohio, U.S.DiedJanuary 21, 1901(1901-01-21) (aged 65)Newtonville, Massachusetts, U.S.OccupationEngineer/InventorAwardsElliott Cresson Medal (1897)Signature Elisha Gray (August 2, 1835 – January 21, 1901) was an American electrical engineer who co-founded the Western Electric Manufacturing Company. Gray is best known for his development of a telephone prototype in 1876 in Highland Park, Illinois. Some rece...

Gearing-class destroyer For other ships with the same name, see USS Holder. USS Holder History United States NameUSS Holder NamesakeRandolph M. Holder BuilderConsolidated Steel Corporation, Orange, Texas Laid down23 April 1945 Launched25 August 1945 Commissioned18 May 1946 Decommissioned1 October 1976 Reclassified DDE-819, 4 March 1950 DD-819, 7 August 1962 Stricken1 October 1976 FateTransferred to Ecuador, 23 February 1977 History Ecuador NameBAE Presidente Eloy Alfaro NamesakeEloy Alfaro Ac...

WeltmeisterJenis produkMobilPemilikWM MotorDiluncurkanJanuari 2015DihentikanOktober 2023PasarCinaSitus webwww.wm-motor.com Showroom juara dunia di Zhengzhou, China Weltmeister (Hanzi: 威马汽车) adalah sebuah merek mobil listrik milik WM Motor Technology Co Ltd, sebuah perusahaan kendaraan yang berbasis di Shanghai dan mengkhususkan diri dalam pembuatan kendaraan bertenaga baterai. Perusahaan tersebut meluncurkan mobil produksi perdananya, EX5 pada Mei 2018 di Beijing Auto Show, dengan...

Paghimo ni bot Lsjbot. Alang sa ubang mga dapit sa mao gihapon nga ngalan, tan-awa ang Meridian Lake. 60°17′06″N 149°22′00″W / 60.28488°N 149.36676°W / 60.28488; -149.36676 Meridian Lake Lanaw Nasod  Tinipong Bansa Estado Alaska Kondado Kenai Peninsula Borough Gitas-on 243 m (797 ft) Tiganos 60°17′06″N 149°22′00″W / 60.28488°N 149.36676°W / 60.28488; -149.36676 Timezone AKST (UTC-9)  - summer (DST) AKDT...