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:

Prolepsis tristis Klasifikasi ilmiah Kerajaan: Animalia Filum: Arthropoda Kelas: Insecta Ordo: Diptera Famili: Tipulidae Genus: Prolepsis Spesies: Prolepsis tristis Prolepsis tristis adalah spesies lalat yang tergolong famili Asilidae. Lalat ini juga merupakan bagian dari genus Prolepsis, ordo Diptera, kelas Insecta, filum Arthropoda, dan kingdom Animalia.[1] Lalat ini mempunyai insting predator yang agresif dan makanannya utamanya adalah serangga lain. Referensi ^ Bisby F.A., Roskov ...

 

 

You can help expand this article with text translated from the corresponding article in Russian. (February 2015) Click [show] for important translation instructions. View a machine-translated version of the Russian article. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wik...

 

 

Увага: це зображення не може бути завантажене до Wikimedia Commons. Згідно із Законом України «Про авторське право і суміжні права» виключні права на використання творів архітектури, містобудування, садово-паркового мистецтва належать виключно їх авторам (частина 4 статті 15 Зак...

جامعة لينيرس   معلومات التأسيس 2010 النوع عامة الموقع الجغرافي إحداثيات 56°51′15″N 14°49′51″E / 56.85416667°N 14.83083333°E / 56.85416667; 14.83083333  المدينة فاكسيو[1]،  وكالمار  الرمز البريدي 35195[1]،  و352 52[1]  البلد سويد سميت باسم كارولوس لينيوس  إحصاءات الأس

 

 

سلسلة من المقالات حولالأساطير الكلتية الأيرلندية الإسكتلندية الويلزية البرتونية الكورنشية المفاهيم الدين الآلهة (قائمة) الأرواحية توتا دي دانان Fomhoraigh فلكلور وأساطير هبرديسية Mythological Cycle Ulster Cycle Fianna Cycle العصر الحديدي البريطاني المهرجانات درويد Bards Vates الدعوات الدينية Otherworl...

 

 

يوم ما اتقابلنابوستر الفيلممعلومات عامةتاريخ الصدور 20 مايو 2009اللغة الأصلية العربيةالبلد  مصرالطاقمالمخرج إسماعيل مرادالكاتب تغريد العصفوري (قصة)زينب عزيز (سيناريو وحوار)البطولة محمود حميدةلبلبةعلا غانمأحمد عزميغادة إبراهيمراندا البحيريميرنا المهندسمحمد نجاتيصناع...

حراما تقسيم إداري البلد  سوريا المحافظة محافظة اللاذقية المسؤولون المنطقة منطقة جبلة الناحية ناحية بيت ياشوط خصائص جغرافية إحداثيات 35°19′N 36°07′E / 35.31°N 36.12°E / 35.31; 36.12 الارتفاع من 440 إلى 500 السكان التعداد السكاني أكثر من 300 نسمة (إحصاء 2004) معلومات أخرى التوقيت +2 ت

 

 

Konkatedral ZagrebGereja Katedral Katolik Yunani Santo Sirilus dan Methodius di Zagrebbahasa Kroasia: Grkokatolička konkatedrala Sv. Ćirila i Metoda u ZagrebuKonkatedral ZagrebLokasiZagrebNegara KroasiaDenominasiGereja Katolik Roma(sui iuris: Gereja Katolik Yunani Kroasia dan Serbia)ArsitekturStatusKatedralStatus fungsionalAktifArsitekHermann BolléGayaBarokAdministrasiKeuskupanEparki Križevci Konkatedral Zagreb atau yang secara resmi bernama Gereja Konkatedral Katolik Yunani Sant...

 

 

Als Quaternionenadler wird ein doppelköpfiger Reichsadler des Heiligen Römischen Reiches bezeichnet, der das Reich durch die Darstellung der Wappen der Glieder (Stände) des Reiches allegorisch darstellt. Symbolik Quaternionenadler aus der Handschrift „Agrippina“ von Heinrich van Beeck Holzschnittzeichnung von Hans Burgkmair dem Älteren aus dem Jahre 1510 Kolorierte Darstellung von Jost de Negker auf der Darstellung von Burgkmair beruhend, 1510 Quaternionenadler von Jost de Negker als ...

Pour les articles homonymes, voir Saint-Nicolas. Cet article est une ébauche concernant une localité flamande. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Saint-Nicolas (nl) Sint-Niklaas L'hôtel de ville. Héraldique Drapeau Administration Pays Belgique Région  Région flamande Communauté  Communauté flamande Province  Province de Flandre-Orientale Arrondissement Saint-Nicolas Bourgmestre...

 

 

Italian cycling team GW–Shimano–SidermecTeam informationUCI codeDRARegisteredItaly (1996–2022)Colombia (2023–)Founded1996 (1996)Discipline(s)RoadStatusUCI ProTeam (1996–2022)UCI Continental (2023–)BicyclesBottecchiaWebsiteTeam home pageKey personnelGeneral managerGianni SavioTeam name history19961997–19981999200020012002–2005200620072008–20092010–20112012–201420152016–201720172018–202120222023–Gaseosas Glacial–Selle ItaliaKross–Selle ItaliaSelle ItaliaAgua...

 

 

2004 film by Oliver Hirschbiegel DownfallTheatrical release posterDirected byOliver HirschbiegelScreenplay byBernd EichingerBased on Inside Hitler's Bunkerby Joachim Fest Until the Final Hourby Traudl JungeMelissa Müller Produced byBernd EichingerStarring Bruno Ganz Alexandra Maria Lara Corinna Harfouch Ulrich Matthes Juliane Köhler Heino Ferch Christian Berkel Alexander Held Matthias Habich Thomas Kretschmann CinematographyRainer Klausmann[1]Edited byHans Funck[1]Music bySt...

この項目では、音楽について説明しています。核分裂・核融合の産業利用については「平和のための原子力」をご覧ください。 アトムス・フォー・ピースAtoms For Peace アトムス・フォー・ピース(2010年)基本情報出身地 アメリカ合衆国 カリフォルニア州ロサンゼルスジャンル インディー・ロックオルタナティヴ・ロックエレクトロニカエクスペリメンタル・ロックIDM...

 

 

لوفت شفباو زيبلن Luftschiffbau Zeppelin تاريخ التأسيس 1908  الدولة الإمبراطورية الألمانية ألمانيا  أهم الشخصيات المؤسس فرديناند فون زبلين المقر الرئيسي فريدريشسهافن  الشركات التابعة زبلين الألمانية لشحن  الصناعة طيران  المنتجات فاو-2،  وسفينة هوائية  موقع ويب الموق...

 

 

2017 book by Mark Bray Antifa: The Anti-Fascist Handbook AuthorMark BrayAudio read byKeith SzarabajkaCountryUnited StatesLanguageEnglishSubjectSocial movementsPublisherMelville HousePublication dateAugust 2017Pages288ISBN978-1-61219-703-6 Antifa: The Anti-Fascist Handbook is a 2017 book written by historian Mark Bray and published by Melville House Publishing, which explores the history of anti-fascist movements since the 1920s and 1930s and their contemporary resurgence. Content An...

天意劉德華的录音室专辑发行日期1994年11月25日类型華語流行音樂唱片公司飛碟唱片制作人李安修劉德華专辑年表 五時三十分(1994年) 天意(1994年) Memories(1995年) 《天意》是香港歌手劉德華於1994年發行的國語專輯[1]。 簡介 这是华仔的代表性专辑之一。 曲目 次序 歌名 作曲 填詞 時間 01 天意 陳耀川 李安修 04:32 02 友誼歷久一樣濃 陈耀川 劉德華 04:06 03 沒有人可以...

 

 

Piano compositions by George Gershwin This article is about Gershwin's 1926 piano suite. For other uses, see Three Preludes (disambiguation). This article includes a list of general references, but it lacks sufficient corresponding inline citations. Please help to improve this article by introducing more precise citations. (October 2017) (Learn how and when to remove this template message) Three Preludes is a collection of short piano pieces by George Gershwin, which were first performed by t...

 

 

  ميّز عن خط زمني لفيروسات الحاسوب والديدان. الجدول التالي يوضح بعض المعلومات عن ديدان worm الحاسوب المشهورة وأصولها وتاريخ عزلها ونوعها وأسمائها المعروفة هذه القائمة غير مكتملة. فضلاً ساهم في تطويرها بإضافة مزيد من المعلومات ولا تنسَ الاستشهاد بمصادر موثوق بها. الاسم ...

Nervous system benign neoplasm that is characterized as a nerve tissue tumor Medical conditionNeuromaSolitary circumscribed neuromaSpecialtyOncology  A neuroma (/njʊəˈroʊmə/; plural: neuromata or neuromas) is a growth or tumor of nerve tissue.[1] Neuromas tend to be benign (i.e. not cancerous); many nerve tumors, including those that are commonly malignant, are nowadays referred to by other terms. Neuromas can arise from different types of nervous tissue, including the nerve...

 

 

Villa dei PapiriVilla dei PisoniLa villaCiviltàRomani UtilizzoVilla Epocadal I secolo a.C. al 79 LocalizzazioneStato Italia ComuneErcolano ScaviData scoperta1750 Date scavi1750-1761, 1764-1765, 1985, 1996-1998, 2002- AmministrazionePatrimonioScavi archeologici di Ercolano EnteParco archeologico di Ercolano VisitabileNo Sito webercolano.beniculturali.it/ Mappa di localizzazione Modifica dati su Wikidata · ManualeCoordinate: 40°48′26.82″N 14°20′40.92″E / 40...

 

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!