Programming Search⌘K

Taskintro

Map over a list

Also called apply a function to each item, transform a list, select, collect, list comprehension, apply a callback to an array.

Make a new list with the result of a function for each item of a list, in the same order, and know when the map runs.

Task

Make a new list with the result of a function for each item of a list. The function square_all(items) returns the square of each integer, in the same order. For example, square_all([1, 2, 3]) is [1, 4, 9], and square_all([-3, -1]) is [9, 1].

The result has the same length as the input, and the input list does not change. Each item is from -46340 to 46340, so each square fits in a 32-bit signed integer.

Solutions

Language Square each item
Python [x * x for x in items]
JavaScript, TypeScript items.map((x) => x * x)
Java Arrays.stream(items).map(x -> x * x).toArray()
C# items.Select(x => x * x).ToArray()
Go make a slice of the same length, and a loop
Rust items.iter().map(|x| x * x).collect()
C a loop that writes out[i]
C++ std::ranges::transform with std::back_inserter
Bash a loop that prints $((x * x))
  • Python. map returns "an iterator that applies function to every item of iterable, yielding the results"1. The solution uses a list comprehension, which makes a list.
  • Java. toArray is the terminal operation, and it makes the new array.
  • C#. ToArray runs the query at once and keeps the result.
  • Rust. "as map() is lazy, it is best used when"2 the code already works with other iterators. collect runs the map and makes the vector.
  • C. The caller gives an out array with room for n items.
  • C++. std::back_inserter adds each result to the end of the vector. "std::transform does not guarantee in-order application of unary_op or binary_op"3, so the function must not depend on the order of the calls.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • empty: the map of an empty list is an empty list.
  • single: one item gives one result.
  • negative and zero: the square of a negative item is positive, and the square of 0 is 0.
  • limit: 46340 and -46340 give 2147395600, which fits in a 32-bit signed integer. The square of 46341 does not fit.
  • order and duplicates: result i comes from item i, and equal items give equal results.

Pitfalls

  • Python map gives a one-pass iterator. The second list(squares) in the example is empty, because the first one used all the items. Make a list if you need the result more than once:
squares = map(lambda x: x * x, [1, 2, 3])
print(list(squares))
print(list(squares))
Output
[1, 4, 9]
[]
  • JavaScript map(parseInt) gives NaN. map gives the callback the item, the index and the array. "parseInt is often used with one argument, but takes two"4, and the second one is the radix. "While one might expect [1, 2, 3], the actual result is [1, NaN, NaN]"4:
console.log(["1", "2", "3"].map(parseInt));
console.log(["1", "2", "3"].map((s) => parseInt(s, 10)));
Output
[ 1, NaN, NaN ]
[ 1, 2, 3 ]
  • Java streams run once. "A stream should be operated on (invoking an intermediate or terminal stream operation) only once"5. "A stream implementation may throw IllegalStateException if it detects that the stream is being reused"5:
import java.util.Arrays;
import java.util.stream.IntStream;

public class Main {
  public static void main(String[] args) {
    IntStream squares = IntStream.of(1, 2, 3).map(x -> x * x);
    System.out.println(Arrays.toString(squares.toArray()));
    try {
      squares.toArray();
    } catch (IllegalStateException e) {
      System.out.println("IllegalStateException");
    }
  }
}
Output
[1, 4, 9]
IllegalStateException
  • C# Select runs again each time. "This method is implemented by using deferred execution"6. In the example, Sum and Max each run the function on the 3 items, so it runs 6 times. ToList runs it 3 times:
int calls = 0;
var squares = new[] { 1, 2, 3 }.Select(x => { calls++; return x * x; });
Console.WriteLine($"{squares.Sum()} {squares.Max()} calls={calls}");
calls = 0;
var list = new[] { 1, 2, 3 }.Select(x => { calls++; return x * x; }).ToList();
Console.WriteLine($"{list.Sum()} {list.Max()} calls={calls}");
Output
14 9 calls=6
14 9 calls=3
  • Go range gives a copy of the item. "the iteration values are assigned to the respective variables as in an assignment statement"7. An assignment to x does not change the slice. Write to items[i]:
package main

import "fmt"

func main() {
	items := []int{1, 2, 3}
	for _, x := range items {
		x = x * x
	}
	fmt.Println(items)
	for i, x := range items {
		items[i] = x * x
	}
	fmt.Println(items)
}
Output
[1 2 3]
[1 4 9]
  • Rust map does nothing until a consumer runs it. In the example, the map that is dropped does not call the closure. collect calls it once for each item:
fn main() {
    let items = [1, 2, 3];
    let mut calls = 0;
    let squares = items.iter().map(|x| {
        calls += 1;
        x * x
    });
    drop(squares);
    println!("calls={calls}");
    let v: Vec<i32> = items
        .iter()
        .map(|x| {
            calls += 1;
            x * x
        })
        .collect();
    println!("{v:?} calls={calls}");
}
Output
calls=0
[1, 4, 9] calls=3
  • C map in place changes the array of the caller. An array argument "undergoes an implicit conversion to the pointer to its first element"8. So the function gets a pointer, and it writes to the array of the caller. Write to a separate out array if the caller needs the input:
#include <stdio.h>

// The parameter a is a pointer to the first item of the array of the caller.
static void square_in_place(int *a, size_t n) {
    for (size_t i = 0; i < n; i++) {
        a[i] = a[i] * a[i];
    }
}

int main(void) {
    int items[] = {1, 2, 3};
    square_in_place(items, 3);
    printf("%d %d %d\n", items[0], items[1], items[2]);
    return 0;
}
Output
1 4 9
  • C++ views::transform runs the function each time. A view does not keep the results. In the example, two loops over the view call the function 6 times, and the copy to a vector calls it 3 more times:
#include <iostream>
#include <ranges>
#include <vector>

int main() {
    int calls = 0;
    std::vector<int> v{1, 2, 3};
    auto squares = v | std::views::transform([&calls](int x) {
                       ++calls;
                       return x * x;
                   });
    int sum = 0;
    for (int x : squares) {
        sum += x;
    }
    for (int x : squares) {
        sum += x;
    }
    std::cout << sum << " calls=" << calls << "\n";
    std::vector<int> out(squares.begin(), squares.end());
    std::cout << out.size() << " calls=" << calls << "\n";
}
Output
28 calls=6
3 calls=9
  • Bash for gives a copy of each word. The loop runs "with name bound to the current word"9. An assignment to x does not change the array. Loop over the indices ${!a[@]}:
a=(1 2 3)
for x in "${a[@]}"; do
  x=$((x * x))
done
echo "${a[@]}"
for i in "${!a[@]}"; do
  a[i]=$((a[i] * a[i]))
done
echo "${a[@]}"
Output
1 2 3
1 4 9

Code

The build runs the native tests of each language in a pinned toolchain.

square_all.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/map-over-a-list/.

def square_all(items: list[int]) -> list[int]:
    """Return a new list with the square of each item, in the same order."""
    # A list comprehension makes a list. map(...) makes a one-pass iterator.
    return [x * x for x in items]
test_square_all.py 24 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/map-over-a-list/.

import pytest

from square_all import square_all

CASES = {
    "small": ([1, 2, 3], [1, 4, 9]),
    "tens": ([5, 10], [25, 100]),
    "empty": ([], []),
    "single": ([7], [49]),
    "negative": ([-3, -1], [9, 1]),
    "zero": ([0], [0]),
    "limit": ([46340, -46340], [2147395600, 2147395600]),
    "order": ([3, 1, 2], [9, 1, 4]),
    "duplicates": ([2, 2], [4, 4]),
}


@pytest.mark.parametrize("name", CASES)
def test_square_all(name):
    items, want = CASES[name]
    assert square_all(items) == want
square_all.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

#include "square_all.hpp"

#include <algorithm>
#include <iterator>
#include <span>
#include <vector>

std::vector<int> square_all(std::span<const int> items) {
    std::vector<int> out;
    out.reserve(items.size());
    // back_inserter adds each result to out. A plain out.begin() would write
    // past the end of the empty vector.
    std::ranges::transform(items, std::back_inserter(out), [](int x) { return x * x; });
    return out;
}
square_all.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

#pragma once

#include <span>
#include <vector>

// square_all returns a new vector with the square of each item, in the same
// order.
std::vector<int> square_all(std::span<const int> items);
test_square_all.cpp 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

#include "square_all.hpp"

#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, const std::vector<int> &items, const std::vector<int> &want) {
    if (square_all(items) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("small", std::vector<int>{1, 2, 3}, {1, 4, 9});
    check("tens", std::vector<int>{5, 10}, {25, 100});
    check("empty", std::vector<int>{}, std::vector<int>{});
    check("single", std::vector<int>{7}, {49});
    check("negative", std::vector<int>{-3, -1}, {9, 1});
    check("zero", std::vector<int>{0}, {0});
    check("limit", std::vector<int>{46340, -46340}, {2147395600, 2147395600});
    check("order", std::vector<int>{3, 1, 2}, {9, 1, 4});
    check("duplicates", std::vector<int>{2, 2}, {4, 4});
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
SquareAll.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

import java.util.Arrays;

final class SquareAll {
  private SquareAll() {}

  /** Returns a new array with the square of each item, in the same order. */
  static int[] squareAll(int[] items) {
    return Arrays.stream(items).map(x -> x * x).toArray();
  }
}
SquareAllTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;

import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class SquareAllTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("small", new int[] {1, 2, 3}, new int[] {1, 4, 9}),
        Arguments.of("tens", new int[] {5, 10}, new int[] {25, 100}),
        Arguments.of("empty", new int[] {}, new int[] {}),
        Arguments.of("single", new int[] {7}, new int[] {49}),
        Arguments.of("negative", new int[] {-3, -1}, new int[] {9, 1}),
        Arguments.of("zero", new int[] {0}, new int[] {0}),
        Arguments.of("limit", new int[] {46340, -46340}, new int[] {2147395600, 2147395600}),
        Arguments.of("order", new int[] {3, 1, 2}, new int[] {9, 1, 4}),
        Arguments.of("duplicates", new int[] {2, 2}, new int[] {4, 4}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void squareAll(String name, int[] items, int[] want) {
    assertArrayEquals(want, SquareAll.squareAll(items));
  }
}
square_all.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

#include "square_all.h"

void square_all(const int *items, size_t n, int *out) {
    for (size_t i = 0; i < n; i++) {
        out[i] = items[i] * items[i];
    }
}
square_all.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

#ifndef SQUARE_ALL_H
#define SQUARE_ALL_H

#include <stddef.h>

// square_all writes the square of items[i] to out[i] for each i in [0, n).
// out must have room for n items. Each item x must have |x| <= 46340, so
// that x * x fits in a 32-bit int.
void square_all(const int *items, size_t n, int *out);

#endif
test_square_all.c 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

#include "square_all.h"

#include <stdbool.h>
#include <stdio.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

// Each list has a 0 at the end when it is empty, because C has no empty
// array. The counts n and m give the real lengths.
static void check(const char *name, const int *got, size_t k, const int *want, size_t m) {
    bool ok = k == m;
    for (size_t i = 0; ok && i < m; i++) {
        ok = got[i] == want[i];
    }
    if (!ok) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

#define CHECK(name, n, given, m, want)  \
    do {                                \
        const int g[] = given;          \
        const int w[] = want;           \
        int out[sizeof g / sizeof g[0]]; \
        square_all(g, n, out); \
        size_t k = n; \
        check(name, out, k, w, m);      \
    } while (0)

int main(void) {
    CHECK("small", 3, L(1, 2, 3), 3, L(1, 4, 9));
    CHECK("tens", 2, L(5, 10), 2, L(25, 100));
    CHECK("empty", 0, L(0), 0, L(0));
    CHECK("single", 1, L(7), 1, L(49));
    CHECK("negative", 2, L(-3, -1), 2, L(9, 1));
    CHECK("zero", 1, L(0), 1, L(0));
    CHECK("limit", 2, L(46340, -46340), 2, L(2147395600, 2147395600));
    CHECK("order", 3, L(3, 1, 2), 3, L(9, 1, 4));
    CHECK("duplicates", 2, L(2, 2), 2, L(4, 4));
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
SquareAll.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

using System.Linq;

public static class SquareAll
{
    // ToArray runs the query now. Without it, Select runs each time the
    // result is read.
    public static int[] Map(int[] items) => items.Select(x => x * x).ToArray();
}
SquareAllTests.cs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

using Xunit;

public sealed class SquareAllTests
{
    public static TheoryData<string, int[], int[]> Cases => new()
    {
        { "small", new int[] { 1, 2, 3 }, new int[] { 1, 4, 9 } },
        { "tens", new int[] { 5, 10 }, new int[] { 25, 100 } },
        { "empty", new int[0], new int[0] },
        { "single", new int[] { 7 }, new int[] { 49 } },
        { "negative", new int[] { -3, -1 }, new int[] { 9, 1 } },
        { "zero", new int[] { 0 }, new int[] { 0 } },
        { "limit", new int[] { 46340, -46340 }, new int[] { 2147395600, 2147395600 } },
        { "order", new int[] { 3, 1, 2 }, new int[] { 9, 1, 4 } },
        { "duplicates", new int[] { 2, 2 }, new int[] { 4, 4 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, SquareAll.Map(items));
    }
}
square_all.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

/**
 * @param {number[]} items
 * @returns {number[]}
 */
export function squareAll(items) {
  // map makes a new array and does not change items.
  return items.map((x) => x * x);
}
square_all.test.js 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { squareAll } from "./square_all.js";

const cases = [
  ["small", [1, 2, 3], [1, 4, 9]],
  ["tens", [5, 10], [25, 100]],
  ["empty", [], []],
  ["single", [7], [49]],
  ["negative", [-3, -1], [9, 1]],
  ["zero", [0], [0]],
  ["limit", [46340, -46340], [2147395600, 2147395600]],
  ["order", [3, 1, 2], [9, 1, 4]],
  ["duplicates", [2, 2], [4, 4]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(squareAll(items), want);
  });
}
square_all.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

export function squareAll(items: readonly number[]): number[] {
  // map makes a new array and does not change items.
  return items.map((x) => x * x);
}
square_all.test.ts 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { squareAll } from "./square_all.ts";

const cases: [string, number[], number[]][] = [
  ["small", [1, 2, 3], [1, 4, 9]],
  ["tens", [5, 10], [25, 100]],
  ["empty", [], []],
  ["single", [7], [49]],
  ["negative", [-3, -1], [9, 1]],
  ["zero", [0], [0]],
  ["limit", [46340, -46340], [2147395600, 2147395600]],
  ["order", [3, 1, 2], [9, 1, 4]],
  ["duplicates", [2, 2], [4, 4]],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.deepEqual(squareAll(items), want);
  });
}
square_all.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

// Package squareall maps a slice to the squares of its items.
package squareall

// SquareAll returns a new slice with the square of each item, in the same
// order. The input slice does not change.
func SquareAll(items []int) []int {
	out := make([]int, len(items))
	for i, x := range items {
		out[i] = x * x
	}
	return out
}
square_all_test.go 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

package squareall

import (
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	want  []int
}{
	{"small", []int{1, 2, 3}, []int{1, 4, 9}},
	{"tens", []int{5, 10}, []int{25, 100}},
	{"empty", []int{}, []int{}},
	{"single", []int{7}, []int{49}},
	{"negative", []int{-3, -1}, []int{9, 1}},
	{"zero", []int{0}, []int{0}},
	{"limit", []int{46340, -46340}, []int{2147395600, 2147395600}},
	{"order", []int{3, 1, 2}, []int{9, 1, 4}},
	{"duplicates", []int{2, 2}, []int{4, 4}},
}

func TestSquareAll(t *testing.T) {
	for _, c := range cases {
		if got := SquareAll(c.items); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}
square_all.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

/// Returns a new vector with the square of each item, in the same order.
pub fn square_all(items: &[i32]) -> Vec<i32> {
    // map is lazy. collect runs it and makes the vector.
    items.iter().map(|x| x * x).collect()
}
tests/square_all_test.rs 22 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/map-over-a-list/.

use algo_map_over_a_list::square_all;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], &[i32])] = &[
        ("small", &[1, 2, 3], &[1, 4, 9]),
        ("tens", &[5, 10], &[25, 100]),
        ("empty", &[], &[]),
        ("single", &[7], &[49]),
        ("negative", &[-3, -1], &[9, 1]),
        ("zero", &[0], &[0]),
        ("limit", &[46340, -46340], &[2147395600, 2147395600]),
        ("order", &[3, 1, 2], &[9, 1, 4]),
        ("duplicates", &[2, 2], &[4, 4]),
    ];
    for &(name, items, want) in cases {
        assert_eq!(square_all(items), want, "{name}");
    }
}
square_all.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/map-over-a-list/.

# square_all ITEM...
# Prints the square of each integer argument, one on each line, in order.
square_all() {
  local x
  for x in "$@"; do
    printf '%s\n' "$((x * x))"
  done
}
test_square_all.bats 35 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/map-over-a-list/.

bats_require_minimum_version 1.5.0

setup() {
  source "$BATS_TEST_DIRNAME/square_all.sh"
}

lines() { # lines ITEM...: prints each item on a line, and nothing for no items
  if (($# > 0)); then printf '%s\n' "$@"; fi
}

check() { # check FUNCTION GIVEN... -- WANT...
  local fn=$1 got want
  shift
  local -a given=()
  while [ "$1" != -- ]; do given+=("$1"); shift; done
  shift
  # The x keeps the trailing newlines, which $(...) removes.
  got=$("$fn" "${given[@]}"; printf x)
  want=$(lines "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "small" { check square_all 1 2 3 -- 1 4 9; }
@test "tens" { check square_all 5 10 -- 25 100; }
@test "empty" { check square_all --; }
@test "single" { check square_all 7 -- 49; }
@test "negative" { check square_all -3 -1 -- 9 1; }
@test "zero" { check square_all 0 -- 0; }
@test "limit" { check square_all 46340 -46340 -- 2147395600 2147395600; }
@test "order" { check square_all 3 1 2 -- 9 1 4; }
@test "duplicates" { check square_all 2 2 -- 4 4; }

References

  1. The Python Standard Library, Built-in Functions, map()
  2. Rust standard library, trait Iterator, map
  3. cppreference.com, std::transform, Notes
  4. MDN Web Docs, Array.prototype.map(), Using parseInt() with map()
  5. Java SE 25 API, Interface Stream, Interface description
  6. .NET API reference, Enumerable.Select method, Remarks
  7. The Go Programming Language Specification, For statements with range clause
  8. cppreference.com, C array declaration, Array to pointer conversion
  9. Bash Reference Manual, 3.2.5.1 Looping Constructs

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source