Lists and Arrays compared across 16 programming languages
Create, extend, filter, and sort lists or arrays.
PyPython
zahlen = [5, 3, 8, 1]
zahlen.append(10)
zahlen.sort()
print(zahlen)
print([z * 2 for z in zahlen if z > 3])
print(sum(zahlen), max(zahlen), len(zahlen))The list comprehension filters and transforms in a single line.
JSJavaScript
const zahlen = [5, 3, 8, 1];
zahlen.push(10);
zahlen.sort((a, b) => a - b);
console.log(zahlen);
console.log(zahlen.filter(z => z > 3).map(z => z * 2));
console.log(zahlen.reduce((s, z) => s + z, 0), Math.max(...zahlen), zahlen.length);sort needs a compare function for numbers; filter, map and reduce return new values.
TSTypeScript
const zahlen: number[] = [5, 3, 8, 1];
zahlen.push(10);
zahlen.sort((a, b) => a - b);
console.log(zahlen);
console.log(zahlen.filter((z) => z > 3).map((z) => z * 2));
console.log(zahlen.reduce((s, z) => s + z, 0), Math.max(...zahlen), zahlen.length);number[] prevents a string from ending up in the array; the callback parameter types are inferred.
JvJava
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> zahlen = new ArrayList<>(List.of(5, 3, 8, 1));
zahlen.add(10);
Collections.sort(zahlen);
System.out.println(zahlen);
System.out.println(zahlen.stream().filter(z -> z > 3).map(z -> z * 2).toList());
System.out.println(zahlen.size() + " " + Collections.max(zahlen));
}
}List.of is immutable, so we copy into an ArrayList. The stream filters and transforms like a list comprehension. Output: [1, 3, 5, 8, 10], [10, 16, 20], 5 10.
CC
#include <stdio.h>
int main(void) {
int zahlen[] = {5, 3, 8, 1};
size_t n = sizeof(zahlen) / sizeof(zahlen[0]);
int summe = 0, max = zahlen[0];
for (size_t i = 0; i < n; i++) {
summe += zahlen[i];
if (zahlen[i] > max) max = zahlen[i];
}
printf("n=%zu sum=%d max=%d\n", n, summe, max);
return 0;
}C arrays have a fixed size; you compute the number of elements with sizeof. For growing lists you need malloc/realloc (see the snippet "Dynamic array").
C++C++
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> zahlen{5, 3, 8, 1};
zahlen.push_back(10);
std::sort(zahlen.begin(), zahlen.end());
for (int z : zahlen) std::cout << z << ' ';
std::cout << "\nSum: " << std::accumulate(zahlen.begin(), zahlen.end(), 0) << '\n';
}The analogue of a list is std::vector. Sorting and summing are done by algorithms from <algorithm> and <numeric> using iterators.
C#C#
var zahlen = new List<int> { 5, 3, 8, 1 };
zahlen.Add(10);
zahlen.Sort();
Console.WriteLine(string.Join(", ", zahlen));
Console.WriteLine(string.Join(", ", zahlen.Where(z => z > 3).Select(z => z * 2)));
Console.WriteLine($"{zahlen.Sum()} {zahlen.Max()} {zahlen.Count}");Where filters, Select transforms – the C# counterpart to a list comprehension. Output: 1, 3, 5, 8, 10, then 10, 16, 20, then 27 10 5.
GoGo
package main
import (
"fmt"
"slices"
)
func main() {
zahlen := []int{5, 3, 8, 1}
zahlen = append(zahlen, 10)
slices.Sort(zahlen)
fmt.Println(zahlen, len(zahlen))
}Slices are Go's lists; append returns the slice and must be assigned. Output: [1 3 5 8 10] 5. There is no list comprehension – filter with a for loop (see the snippet "Filter and transform a slice").
RsRust
fn main() {
let mut zahlen = vec![5, 3, 8, 1];
zahlen.push(10);
zahlen.sort();
println!("{:?}", zahlen);
let doppelt: Vec<i32> = zahlen.iter().filter(|&&z| z > 3).map(|z| z * 2).collect();
println!("{:?}", doppelt);
println!("{} {:?} {}", zahlen.iter().sum::<i32>(), zahlen.iter().max(), zahlen.len());
}Vec<T> is the growable list. The iterator chain filters and transforms (like a list comprehension); max() returns an Option.
PHPPHP
<?php
$zahlen = [5, 3, 8, 1];
$zahlen[] = 10;
sort($zahlen);
echo implode(", ", $zahlen), "\n";
$doppelt = array_map(fn($z) => $z * 2, array_filter($zahlen, fn($z) => $z > 3));
echo implode(", ", $doppelt), "\n";
echo array_sum($zahlen), " ", max($zahlen), " ", count($zahlen), "\n";PHP has no list literal with comprehension: array_filter and array_map (with arrow functions) do the same. Output: 1, 3, 5, 8, 10, then 10, 16, 20, then 27 10 5.
RbRuby
zahlen = [5, 3, 8, 1]
zahlen << 10
zahlen.sort!
puts zahlen.inspect
puts zahlen.select { |z| z > 3 }.map { |z| z * 2 }.inspect
puts "#{zahlen.sum} #{zahlen.max} #{zahlen.size}"<< appends, sort! sorts in place. select filters, map transforms – chains replace loops. Output: [1, 3, 5, 8, 10], [10, 16, 20], 27 10 5.
SwSwift
var zahlen = [5, 3, 8, 1]
zahlen.append(10)
zahlen.sort()
print(zahlen)
print(zahlen.filter { $0 > 3 }.map { $0 * 2 })
print(zahlen.reduce(0, +), zahlen.max() ?? 0, zahlen.count)filter and map with a trailing closure replace list comprehensions; max() returns an optional, hence ?? 0.
KtKotlin
fun main() {
val zahlen = mutableListOf(5, 3, 8, 1)
zahlen.add(10)
zahlen.sort()
println(zahlen)
println(zahlen.filter { it > 3 }.map { it * 2 })
println("${zahlen.size} ${zahlen.max()}")
}filter and map are available directly on collections. Output: [1, 3, 5, 8, 10], [10, 16, 20], and 5 10.
SQLSQL
SELECT id, name, kategorie
FROM produkte
WHERE kategorie IN ('Elektronik', 'Möbel')
ORDER BY name;
-- List as a table with VALUES
WITH farben(id, name) AS (VALUES (1, 'rot'), (2, 'grün'), (3, 'blau'))
SELECT * FROM farben;The result of a SELECT is always a table, i.e. a "list of rows". IN (…) checks membership in a list of values, and VALUES creates a table directly from literals.
shBash
zahlen=(5 3 8 1)
zahlen+=(10)
echo "Count: ${#zahlen[@]}"
echo "First: ${zahlen[0]}, last: ${zahlen[@]: -1}"
echo "All: ${zahlen[@]}"
sortiert=$(printf '%s\n' "${zahlen[@]}" | sort -n | tr '\n' ' ')
echo "Sorted: $sortiert"Arrays are created in parentheses, += appends, ${#arr[@]} counts. ${arr[@]: -1} returns the last element (with Bash 4.3+ ${arr[-1]} also works). You delegate sorting to sort.
</>HTML & CSS
<!DOCTYPE html>
<style>body{font:16px system-ui,sans-serif;margin:12px;background:#fff;color:#222}
ul.check { list-style: none; padding-left: 0; }
ul.check li::before { content: "✔ "; color: seagreen; }
ol.schritte li { margin-bottom: 4px; }
ol.schritte li::marker { font-weight: 700; color: #e34f26; }
</style>
<h3>Shopping List</h3>
<ul class="check"><li>Milk</li><li>Bread</li><li>Coffee</li></ul>
<h3>Instructions</h3>
<ol class="schritte"><li>Create a file</li><li>Write HTML</li><li>Open in the browser</li></ol><ul> for unordered, <ol> for numbered lists with <li> entries. Navigation menus are lists as well. You control the appearance (symbols, counters) with list-style, ::marker and ::before.