Programming Search⌘K

Taskintro

Slice a list

Also called sublist, subarray, slice an array, get a range of a list, copy part of a list, take a sublist, extract a range, list slicing.

Copy the items from a start position up to, but not including, a stop position into a new list, and know which languages copy, which share storage, and which clamp a bad range.

Task

Copy a part of a list into a new list. The function slice(items, start, stop) returns the items from position start up to, but not including, position stop. For example, slice([1, 2, 3, 4, 5], 1, 3) is [2, 3]. The result has stop - start items.

The positions start at 0, and 0 <= start <= stop <= len(items). When start equals stop, the result is empty. A range out of these bounds is an error, and the function must not cut it to fit. The result is a new list: a change to it must not change items, and items must not change. Each item is a 32-bit signed integer, and the list has 0 to 1000 items.

Solutions

Language A copy of items[start:stop] Bad range
Python items[start:stop] the slice clamps it, so check first
JavaScript, TypeScript items.slice(start, stop) the slice clamps it, so check first
Java Arrays.copyOfRange(items, start, stop) Objects.checkFromToIndex throws
C# items[start..stop] ArgumentOutOfRangeException
Go slices.Clone(items[start:stop]) a run-time panic
Rust items[start..stop].to_vec() a panic, or None from get
C malloc and memcpy of stop - start items check first
C++ std::vector<int>(first + start, first + stop) check first
Bash ("${items[@]:start:stop-start}") check first
  • Python. "The slice of s from i to j is defined as the sequence of items with index k such that i <= k < j"1. A slice of a list is a new list. The solution checks the bounds first, because a slice does not raise an error for a bad range.
  • JavaScript. slice "returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included)"2. "The original array will not be modified"2. TypeScript uses the same method on a readonly number[].
  • Java. copyOfRange copies a range of an array, and its to argument is "the final index of the range to be copied, exclusive. (This index may lie outside the array.)"3. Past the end, the copy gets zeros, so the solution checks stop with Objects.checkFromToIndex first.
  • C#. In start..stop, "The left-hand operand is an inclusive start of a range. The right-hand operand is an exclusive end of a range"4. A range of an array is a new array, and a bad range throws ArgumentOutOfRangeException.
  • Go. "For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range"5. For a slice, the upper bound is the capacity. The result of items[start:stop] "shares its underlying array with the operand"5, so the solution copies it with slices.Clone. The solution uses items[start:stop:stop], so that a stop past the length panics, even when the capacity is larger.
  • Rust. &items[start..stop] borrows a part of the slice, and to_vec "Copies self into a new Vec"6. The method get returns "the subslice corresponding to that range, or None if out of bounds"6.
  • C. C has no slice. The solution checks the range, allocates stop - start items, and copies them with memcpy. The caller must free the result.
  • C++. The constructor with two iterators "Constructs a vector with the contents of the range [first, last)"7. The solution checks the range and makes the vector from a std::span.
  • Bash. For ${items[@]:offset:length}, "the result is the length members of the array beginning with ${parameter[offset]}"8. The second number is a length, so the solution passes stop-start. The solution prints one item on each line.

Edge cases

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

  • empty-list: the only range of an empty list is 0 to 0, and the result is empty.
  • empty-slice: when start equals stop, the result is empty, and the list does not need to be empty.
  • whole: slice(items, 0, len(items)) is a copy of the whole list.
  • single and last-one: a range of one item gives a list of one item, not the item.
  • at-end: start and stop can both be len(items). The result is empty, and this is not an error.
  • limit: the items can be the largest and the smallest 32-bit integers.
  • Each test also changes the first item of the result and checks that items does not change. This test finds a result that shares storage with the input. The tests also check that stop past the end and start after stop are errors. The concept page slice tells which languages share storage.

Pitfalls

  • Python slices clamp a bad range and count negative positions from the end. "If i or j is greater than len(s), use len(s)"1, and "If i is greater than or equal to j, the slice is empty"1. So a range past the end gives a short list and no error. "If i or j is negative, the index is relative to the end of sequence s"1, so -1 is the last item. Check the bounds when a bad range is a bug:
a = [1, 2, 3]
print(a[1:10], a[5:9], a[2:1])
print(a[-1:], a[:-1])
Output
[2, 3] [] []
[3] [1, 2]
  • JavaScript splice removes the items. splice "changes the contents of an array by removing or replacing existing elements and/or adding new elements in place"9. Its second argument is a count, not a stop position. slice does not change the array:
const a = [1, 2, 3, 4];
console.log(a.slice(1, 3), a);
console.log(a.splice(1, 3), a);
Output
[ 2, 3 ] [ 1, 2, 3, 4 ]
[ 2, 3, 4 ] [ 1 ]
  • Java subList is a view, not a copy. "The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa"10. Also, "The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list"10. For an ArrayList, the view then throws ConcurrentModificationException. Copy the view to keep it:
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<Integer> a = new ArrayList<>(List.of(1, 2, 3, 4));
    List<Integer> view = a.subList(1, 3);
    view.set(0, 9);
    System.out.println(a);
    List<Integer> copy = new ArrayList<>(view);
    a.add(5);
    try {
      System.out.println(view.size());
    } catch (ConcurrentModificationException e) {
      System.out.println("ConcurrentModificationException");
    }
    System.out.println(copy);
  }
}
Output
[1, 9, 3, 4]
ConcurrentModificationException
[9, 3]
  • C# GetRange takes a count, but a range takes an end. GetRange(index, count) "Creates a shallow copy of a range of elements"11, and its second argument is the number of items. The range 1..3 stops before position 34. So GetRange(1, 3) has three items and [1..3] has two:
var list = new List<int> { 1, 2, 3, 4, 5 };
int[] array = [1, 2, 3, 4, 5];
Console.WriteLine(string.Join(",", list.GetRange(1, 3)));
Console.WriteLine(string.Join(",", array[1..3]));
Console.WriteLine(string.Join(",", array[^2..]));
Output
2,3,4
2,3
4,5
  • Go a slice expression does not copy. The result "shares its underlying array with the operand"5. So a change to the slice changes the original, and append to the slice can write over the next item of the original. Copy the slice with slices.Clone when the parts must be separate:
package main

import (
	"fmt"
	"slices"
)

func main() {
	a := []int{1, 2, 3, 4}
	s := a[1:3]
	s[0] = 9
	fmt.Println(a)
	s = append(s, 7)
	fmt.Println(a)
	c := slices.Clone(a[1:3])
	c[0] = 0
	fmt.Println(a, c)
}
Output
[1 9 3 4]
[1 9 3 7]
[1 9 3 7] [0 3]
  • Rust a backward range is empty, but a slice with it panics. "The range start..end contains all values with start <= x < end. It is empty if start >= end"12. But items[2..1] panics, and so does a range past the end. Use get to receive None for a bad range6:
fn main() {
    let a = [1, 2, 3];
    println!("{} {}", (2..1).is_empty(), (2..1).count());
    println!("{:?} {:?} {:?}", a.get(1..3), a.get(2..5), a.get(2..1));
}
Output
true 0
Some([2, 3]) None None
  • C stop - start wraps when start is larger. For an unsigned type such as size_t, the arithmetic is modulo 2 to the power of the bit count, and "subtracting one from 0 gives UINT_MAX"13. So stop - start with start > stop is a very large count, not a negative one. Check start <= stop before the subtraction. The output is from a machine with a 64-bit size_t:
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>

int main(void) {
    size_t start = 3;
    size_t stop = 1;
    size_t k = stop - start;
    printf("%zu\n", k);
    printf("%d\n", k == SIZE_MAX - 1);
    return 0;
}
Output
18446744073709551614
1
  • C++ subspan takes a count and does not copy. With two arguments, "the subview contains Count elements starting from the Offsetth"14. So subspan(1, 3) has three items, not the items from 1 to 3. A span is a view: a change through it changes the vector. Make a vector from the span to copy the items:
#include <iostream>
#include <span>
#include <vector>

int main() {
    std::vector<int> v{1, 2, 3, 4, 5};
    std::span<int> part = std::span<int>(v).subspan(1, 3);
    std::cout << part.size() << " " << part[0] << " " << part[2] << "\n";
    part[0] = 9;
    std::cout << v[1] << "\n";
    std::vector<int> copy(part.begin(), part.end());
    copy[0] = 0;
    std::cout << v[1] << " " << copy[0] << "\n";
}
Output
3 2 4
9
9 0
  • Bash ${a[@]:-1} is not the last item. The :- form gives a default value when the variable is unset or null, so it gives the whole array here. "Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the ‘:-’ expansion"8. Put a space before the minus sign:
a=(1 2 3)
echo "${a[@]:-1}"
echo "${a[@]: -1}"
echo "${a[@]:1:2}"
Output
1 2 3
3
2 3

Code

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

slice_list.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/slice-a-list/.

def slice_list(items: list[int], start: int, stop: int) -> list[int]:
    """Return a new list of items[start] up to, but not including, items[stop]."""
    if not 0 <= start <= stop <= len(items):
        # A slice would not fail here: it clamps the bounds.
        raise IndexError((start, stop))
    return items[start:stop]
test_slice_list.py 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/slice-a-list/.

import pytest

from slice_list import slice_list

CASES = {
    "middle": ([1, 2, 3, 4, 5], 1, 3, [2, 3]),
    "prefix": ([1, 2, 3], 0, 2, [1, 2]),
    "suffix": ([1, 2, 3], 1, 3, [2, 3]),
    "empty-list": ([], 0, 0, []),
    "empty-slice": ([1, 2, 3], 2, 2, []),
    "whole": ([1, 2, 3], 0, 3, [1, 2, 3]),
    "single": ([7], 0, 1, [7]),
    "last-one": ([1, 2, 3], 2, 3, [3]),
    "at-end": ([1, 2, 3], 3, 3, []),
    "limit": ([2147483647, -2147483648, 0], 0, 2, [2147483647, -2147483648]),
}


@pytest.mark.parametrize("name", CASES)
def test_slice_list(name):
    items, start, stop, want = CASES[name]
    items0 = list(items)
    got = slice_list(items, start, stop)
    assert got == want
    if got:
        got[0] ^= 1
    assert items == items0


@pytest.mark.parametrize("start, stop", [(0, 4), (2, 1)])
def test_bad_range(start, stop):
    with pytest.raises(IndexError):
        slice_list([1, 2, 3], start, stop)
slice_list.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

#include "slice_list.hpp"

#include <cstddef>
#include <span>
#include <stdexcept>
#include <vector>

std::vector<int> slice_list(std::span<const int> items, std::size_t start, std::size_t stop) {
    if (start > stop || stop > items.size()) {
        throw std::out_of_range("slice_list: the range is out of bounds");
    }
    // subspan takes an offset and a count. The vector copies the items.
    const auto part = items.subspan(start, stop - start);
    return std::vector<int>(part.begin(), part.end());
}
slice_list.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

#pragma once

#include <cstddef>
#include <span>
#include <vector>

// slice_list returns a new vector of items[start] up to, but not including,
// items[stop]. It throws std::out_of_range when start > stop or stop > size.
std::vector<int> slice_list(std::span<const int> items, std::size_t start, std::size_t stop);
test_slice_list.cpp 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

#include "slice_list.hpp"

#include <climits>
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string_view>
#include <vector>

static int failures = 0;

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

static bool throws(std::size_t start, std::size_t stop) {
    const std::vector<int> three{1, 2, 3};
    try {
        slice_list(three, start, stop);
    } catch (const std::out_of_range &) {
        return true;
    }
    return false;
}

int main() {
    check("middle", std::vector<int>{1, 2, 3, 4, 5}, 1, 3, std::vector<int>{2, 3});
    check("prefix", std::vector<int>{1, 2, 3}, 0, 2, std::vector<int>{1, 2});
    check("suffix", std::vector<int>{1, 2, 3}, 1, 3, std::vector<int>{2, 3});
    check("empty-list", std::vector<int>{}, 0, 0, std::vector<int>{});
    check("empty-slice", std::vector<int>{1, 2, 3}, 2, 2, std::vector<int>{});
    check("whole", std::vector<int>{1, 2, 3}, 0, 3, std::vector<int>{1, 2, 3});
    check("single", std::vector<int>{7}, 0, 1, std::vector<int>{7});
    check("last-one", std::vector<int>{1, 2, 3}, 2, 3, std::vector<int>{3});
    check("at-end", std::vector<int>{1, 2, 3}, 3, 3, std::vector<int>{});
    check("limit", std::vector<int>{INT_MAX, INT_MIN, 0}, 0, 2, std::vector<int>{INT_MAX, INT_MIN});
    if (!throws(0, 4) || !throws(2, 1)) {
        std::cerr << "case bad-range failed\n";
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
SliceList.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

import java.util.Arrays;
import java.util.Objects;

final class SliceList {
  private SliceList() {}

  /** Returns a new array of items[start] up to, but not including, items[stop]. */
  static int[] slice(int[] items, int start, int stop) {
    // copyOfRange pads with zeros when stop is past the end, so check first.
    Objects.checkFromToIndex(start, stop, items.length);
    return Arrays.copyOfRange(items, start, stop);
  }
}
SliceListTest.java 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

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

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

class SliceListTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("middle", new int[] {1, 2, 3, 4, 5}, 1, 3, new int[] {2, 3}),
        Arguments.of("prefix", new int[] {1, 2, 3}, 0, 2, new int[] {1, 2}),
        Arguments.of("suffix", new int[] {1, 2, 3}, 1, 3, new int[] {2, 3}),
        Arguments.of("empty-list", new int[] {}, 0, 0, new int[] {}),
        Arguments.of("empty-slice", new int[] {1, 2, 3}, 2, 2, new int[] {}),
        Arguments.of("whole", new int[] {1, 2, 3}, 0, 3, new int[] {1, 2, 3}),
        Arguments.of("single", new int[] {7}, 0, 1, new int[] {7}),
        Arguments.of("last-one", new int[] {1, 2, 3}, 2, 3, new int[] {3}),
        Arguments.of("at-end", new int[] {1, 2, 3}, 3, 3, new int[] {}),
        Arguments.of("limit", new int[] {2147483647, Integer.MIN_VALUE, 0}, 0, 2, new int[] {2147483647, Integer.MIN_VALUE}));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void slice(String name, int[] items, int start, int stop, int[] want) {
    int[] items0 = items.clone();
    int[] got = SliceList.slice(items, start, stop);
    assertArrayEquals(want, got);
    if (got.length > 0) {
      got[0] ^= 1;
    }
    assertArrayEquals(items0, items);
  }

  @Test
  void badRange() {
    assertThrows(IndexOutOfBoundsException.class, () -> SliceList.slice(new int[] {1, 2, 3}, 0, 4));
    assertThrows(IndexOutOfBoundsException.class, () -> SliceList.slice(new int[] {1, 2, 3}, 2, 1));
  }
}
slice_list.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

#include "slice_list.h"

#include <stdlib.h>
#include <string.h>

int *slice_list(const int *items, size_t n, size_t start, size_t stop) {
    // Check start <= stop first: stop - start wraps around when start > stop.
    if (start > stop || stop > n) {
        return NULL;
    }
    size_t k = stop - start;
    // malloc(0) may return NULL, so ask for at least one item.
    int *out = malloc((k > 0 ? k : 1) * sizeof *out);
    if (out == NULL) {
        return NULL;
    }
    if (k > 0) {
        memcpy(out, items + start, k * sizeof *items);
    }
    return out;
}
slice_list.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

#ifndef SLICE_LIST_H
#define SLICE_LIST_H

#include <stddef.h>

// slice_list returns a new array of the stop - start items items[start] up to,
// but not including, items[stop]. The caller must free it. It returns NULL
// when start > stop, when stop > n, or when malloc fails.
int *slice_list(const int *items, size_t n, size_t start, size_t stop);

#endif
test_slice_list.c 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

#include "slice_list.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int failures = 0;

#define L(...) {__VA_ARGS__}

static void check(const char *name, const int *items, size_t n, size_t start, size_t stop, const int *want) {
    int *out = slice_list(items, n, start, stop);
    if (out == NULL || (stop > start && memcmp(out, want, (stop - start) * sizeof *out) != 0)) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
    free(out);
}

// C has no empty array, so an empty list is the array {0} with a count of 0.
#define CHECK(name, n, items, start, stop, want) \
    do {                                         \
        const int x[] = items;                   \
        const int w[] = want;                    \
        check(name, x, n, start, stop, w);       \
    } while (0)

int main(void) {
    CHECK("middle", 5, L(1, 2, 3, 4, 5), 1, 3, L(2, 3));
    CHECK("prefix", 3, L(1, 2, 3), 0, 2, L(1, 2));
    CHECK("suffix", 3, L(1, 2, 3), 1, 3, L(2, 3));
    CHECK("empty-list", 0, L(0), 0, 0, L(0));
    CHECK("empty-slice", 3, L(1, 2, 3), 2, 2, L(0));
    CHECK("whole", 3, L(1, 2, 3), 0, 3, L(1, 2, 3));
    CHECK("single", 1, L(7), 0, 1, L(7));
    CHECK("last-one", 3, L(1, 2, 3), 2, 3, L(3));
    CHECK("at-end", 3, L(1, 2, 3), 3, 3, L(0));
    CHECK("limit", 3, L(INT_MAX, INT_MIN, 0), 0, 2, L(INT_MAX, INT_MIN));
    const int three[] = {1, 2, 3};
    if (slice_list(three, 3, 0, 4) != NULL || slice_list(three, 3, 2, 1) != NULL) {
        fprintf(stderr, "case bad-range failed\n");
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
SliceList.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

public static class SliceList
{
    // Returns a new array of items[start] up to, but not including, items[stop].
    // The range of an array is a copy, and a bad range throws
    // ArgumentOutOfRangeException.
    public static int[] Of(int[] items, int start, int stop) => items[start..stop];
}
SliceListTests.cs 43 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

using Xunit;

public sealed class SliceListTests
{
    public static TheoryData<string, int[], int, int, int[]> Cases => new()
    {
        { "middle", new int[] { 1, 2, 3, 4, 5 }, 1, 3, new int[] { 2, 3 } },
        { "prefix", new int[] { 1, 2, 3 }, 0, 2, new int[] { 1, 2 } },
        { "suffix", new int[] { 1, 2, 3 }, 1, 3, new int[] { 2, 3 } },
        { "empty-list", new int[0], 0, 0, new int[0] },
        { "empty-slice", new int[] { 1, 2, 3 }, 2, 2, new int[0] },
        { "whole", new int[] { 1, 2, 3 }, 0, 3, new int[] { 1, 2, 3 } },
        { "single", new int[] { 7 }, 0, 1, new int[] { 7 } },
        { "last-one", new int[] { 1, 2, 3 }, 2, 3, new int[] { 3 } },
        { "at-end", new int[] { 1, 2, 3 }, 3, 3, new int[0] },
        { "limit", new int[] { 2147483647, int.MinValue, 0 }, 0, 2, new int[] { 2147483647, int.MinValue } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int start, int stop, int[] want)
    {
        Assert.NotNull(name);
        var items0 = (int[])items.Clone();
        var got = SliceList.Of(items, start, stop);
        Assert.Equal(want, got);
        if (got.Length > 0)
        {
            got[0] ^= 1;
        }
        Assert.Equal(items0, items);
    }

    [Fact]
    public void BadRange()
    {
        Assert.Throws<ArgumentOutOfRangeException>(() => SliceList.Of([1, 2, 3], 0, 4));
        Assert.Throws<ArgumentOutOfRangeException>(() => SliceList.Of([1, 2, 3], 2, 1));
    }
}
slice_list.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

/**
 * Returns a new array of items[start] up to, but not including, items[stop].
 * @param {number[]} items
 * @param {number} start
 * @param {number} stop
 * @returns {number[]}
 */
export function sliceList(items, start, stop) {
  if (!(Number.isInteger(start) && Number.isInteger(stop) && 0 <= start && start <= stop && stop <= items.length)) {
    throw new RangeError(`range ${start}..${stop} is out of bounds`);
  }
  // slice copies and does not change items. splice would remove the items.
  return items.slice(start, stop);
}
slice_list.test.js 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

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

import { sliceList } from "./slice_list.js";

const cases = [
  ["middle", [1, 2, 3, 4, 5], 1, 3, [2, 3]],
  ["prefix", [1, 2, 3], 0, 2, [1, 2]],
  ["suffix", [1, 2, 3], 1, 3, [2, 3]],
  ["empty-list", [], 0, 0, []],
  ["empty-slice", [1, 2, 3], 2, 2, []],
  ["whole", [1, 2, 3], 0, 3, [1, 2, 3]],
  ["single", [7], 0, 1, [7]],
  ["last-one", [1, 2, 3], 2, 3, [3]],
  ["at-end", [1, 2, 3], 3, 3, []],
  ["limit", [2147483647, -2147483648, 0], 0, 2, [2147483647, -2147483648]],
];

for (const [name, items, start, stop, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    const got = sliceList(items, start, stop);
    assert.deepEqual(got, want);
    if (got.length > 0) {
      got[0] ^= 1;
    }
    assert.deepEqual(items, items0);
  });
}

test("bad range", () => {
  assert.throws(() => sliceList([1, 2, 3], 0, 4), RangeError);
  assert.throws(() => sliceList([1, 2, 3], 2, 1), RangeError);
});
slice_list.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

export function sliceList(items: readonly number[], start: number, stop: number): number[] {
  if (!(Number.isInteger(start) && Number.isInteger(stop) && 0 <= start && start <= stop && stop <= items.length)) {
    throw new RangeError(`range ${start}..${stop} is out of bounds`);
  }
  // slice copies and does not change items. splice would remove the items.
  return items.slice(start, stop);
}
slice_list.test.ts 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

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

import { sliceList } from "./slice_list.ts";

const cases: [string, number[], number, number, number[]][] = [
  ["middle", [1, 2, 3, 4, 5], 1, 3, [2, 3]],
  ["prefix", [1, 2, 3], 0, 2, [1, 2]],
  ["suffix", [1, 2, 3], 1, 3, [2, 3]],
  ["empty-list", [], 0, 0, []],
  ["empty-slice", [1, 2, 3], 2, 2, []],
  ["whole", [1, 2, 3], 0, 3, [1, 2, 3]],
  ["single", [7], 0, 1, [7]],
  ["last-one", [1, 2, 3], 2, 3, [3]],
  ["at-end", [1, 2, 3], 3, 3, []],
  ["limit", [2147483647, -2147483648, 0], 0, 2, [2147483647, -2147483648]],
];

for (const [name, items, start, stop, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    const got = sliceList(items, start, stop);
    assert.deepEqual(got, want);
    if (got.length > 0) {
      got[0] ^= 1;
    }
    assert.deepEqual(items, items0);
  });
}

test("bad range", () => {
  assert.throws(() => sliceList([1, 2, 3], 0, 4), RangeError);
  assert.throws(() => sliceList([1, 2, 3], 2, 1), RangeError);
});
slice_list.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

// Package slicelist copies a part of a slice.
package slicelist

import "slices"

// Slice returns a new slice of items[start] up to, but not including,
// items[stop]. items[start:stop] alone would share the array of items, so
// Slice clones it. It panics if the range is out of bounds.
func Slice(items []int, start, stop int) []int {
	return slices.Clone(items[start:stop:stop])
}
slice_list_test.go 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

package slicelist

import (
	"slices"
	"testing"
)

var cases = []struct {
	name        string
	items       []int
	start, stop int
	want        []int
}{
	{"middle", []int{1, 2, 3, 4, 5}, 1, 3, []int{2, 3}},
	{"prefix", []int{1, 2, 3}, 0, 2, []int{1, 2}},
	{"suffix", []int{1, 2, 3}, 1, 3, []int{2, 3}},
	{"empty-list", []int{}, 0, 0, []int{}},
	{"empty-slice", []int{1, 2, 3}, 2, 2, []int{}},
	{"whole", []int{1, 2, 3}, 0, 3, []int{1, 2, 3}},
	{"single", []int{7}, 0, 1, []int{7}},
	{"last-one", []int{1, 2, 3}, 2, 3, []int{3}},
	{"at-end", []int{1, 2, 3}, 3, 3, []int{}},
	{"limit", []int{2147483647, -2147483648, 0}, 0, 2, []int{2147483647, -2147483648}},
}

func TestSlice(t *testing.T) {
	for _, c := range cases {
		items0 := slices.Clone(c.items)
		got := Slice(c.items, c.start, c.stop)
		if !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
		if len(got) > 0 {
			got[0] ^= 1
		}
		if !slices.Equal(c.items, items0) {
			t.Errorf("%s: the input changed", c.name)
		}
	}
}

func TestBadRange(t *testing.T) {
	defer func() {
		if recover() == nil {
			t.Error("no panic for a stop past the end")
		}
	}()
	Slice([]int{1, 2, 3}, 0, 4)
}
slice_list.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

/// Returns a new vector of items[start] up to, but not including, items[stop].
///
/// # Panics
///
/// Panics if start > stop or stop > items.len().
pub fn slice(items: &[i32], start: usize, stop: usize) -> Vec<i32> {
    // &items[start..stop] borrows the items; to_vec copies them.
    items[start..stop].to_vec()
}
tests/slice_list_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/slice-a-list/.

use algo_slice_a_list::slice;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], usize, usize, &[i32])] = &[
        ("middle", &[1, 2, 3, 4, 5], 1, 3, &[2, 3]),
        ("prefix", &[1, 2, 3], 0, 2, &[1, 2]),
        ("suffix", &[1, 2, 3], 1, 3, &[2, 3]),
        ("empty-list", &[], 0, 0, &[]),
        ("empty-slice", &[1, 2, 3], 2, 2, &[]),
        ("whole", &[1, 2, 3], 0, 3, &[1, 2, 3]),
        ("single", &[7], 0, 1, &[7]),
        ("last-one", &[1, 2, 3], 2, 3, &[3]),
        ("at-end", &[1, 2, 3], 3, 3, &[]),
        ("limit", &[2147483647, i32::MIN, 0], 0, 2, &[2147483647, i32::MIN]),
    ];
    for &(name, items, start, stop, want) in cases {
        assert_eq!(slice(items, start, stop), want, "{name}");
    }
}

#[test]
#[should_panic]
fn stop_past_the_end() {
    slice(&[1, 2, 3], 0, 4);
}
slice_list.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/slice-a-list/.

# slice_list START STOP ITEM...
# Prints the items from position START up to, but not including, position
# STOP, one on each line. It returns 1 when the range is out of bounds.
slice_list() {
  local start=$1 stop=$2
  shift 2
  local -a items=("$@")
  if ! [[ $start =~ ^[0-9]+$ && $stop =~ ^[0-9]+$ ]] || ((start > stop || stop > ${#items[@]})); then
    return 1
  fi
  # ${items[@]:offset:length} takes a length, not a stop position.
  local -a part=("${items[@]:start:stop-start}")
  if ((${#part[@]} > 0)); then printf '%s\n' "${part[@]}"; fi
}
test_slice_list.bats 38 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/slice-a-list/.

bats_require_minimum_version 1.5.0

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

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

check() { # check START STOP "ITEMS" -- WANT...
  local start=$1 stop=$2
  local -a items
  read -r -a items <<<"$3"
  shift 4
  local got want
  # The x keeps the trailing newlines, which $(...) removes.
  got=$(slice_list "$start" "$stop" "${items[@]}"; printf x)
  want=$(lines "$@"; printf x)
  [ "$got" = "$want" ] || { printf 'got:  %q\nwant: %q\n' "$got" "$want"; return 1; }
}

@test "middle" { check 1 3 "1 2 3 4 5" -- 2 3; }
@test "prefix" { check 0 2 "1 2 3" -- 1 2; }
@test "suffix" { check 1 3 "1 2 3" -- 2 3; }
@test "empty-list" { check 0 0 "" --; }
@test "empty-slice" { check 2 2 "1 2 3" --; }
@test "whole" { check 0 3 "1 2 3" -- 1 2 3; }
@test "single" { check 0 1 "7" -- 7; }
@test "last-one" { check 2 3 "1 2 3" -- 3; }
@test "at-end" { check 3 3 "1 2 3" --; }
@test "limit" { check 0 2 "2147483647 -2147483648 0" -- 2147483647 -2147483648; }
@test "spaces" { got=$(slice_list 1 3 a "New York" Paris; printf x); [ "$got" = $'New York\nParis\nx' ]; }
@test "bad-range" { if slice_list 0 4 1 2 3 >/dev/null; then return 1; fi; if slice_list 2 1 1 2 3 >/dev/null; then return 1; fi; }

References

  1. The Python Standard Library, Built-in Types, Common Sequence Operations, notes 3, 4 and 5
  2. MDN Web Docs, Array.prototype.slice(), Description and Parameters
  3. Java SE 25 API, Class Arrays, copyOfRange(int[] original, int from, int to)
  4. C# language reference, Member access operators and expressions, Range operator ..
  5. The Go Programming Language Specification, Slice expressions
  6. Rust standard library, Primitive Type slice, to_vec and get
  7. cppreference.com, std::vector constructor, Description, overload 5
  8. Bash Reference Manual, 3.5.3 Shell Parameter Expansion
  9. MDN Web Docs, Array.prototype.splice(), Description
  10. Java SE 25 API, Interface List, subList(int fromIndex, int toIndex)
  11. .NET API reference, List<T>.GetRange(Int32, Int32), Definition and Parameters
  12. Rust standard library, Struct Range, Description
  13. cppreference.com, C arithmetic operators, Overflows
  14. cppreference.com, std::span::subspan, Description

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