Taskintro
Append to a list
Also called add an item to a list, push to an array, insert into a list, add to the end of a list, prepend to a list, insert at an index, grow an array.
Add one item to a list, at the end with append, push or Add, or at a given position with insert, and know what each call returns and when it fails.
- Evidence
- Code in 10 languages
Task
Add one item to a list of integers. The function insert_at(items, index, value) returns a new list with value at position index, and items does not change. An index of len(items) adds the value at the end, and an index of 0 adds it at the front. For example, insert_at([1, 2], 2, 3) is [1, 2, 3], and insert_at([2, 3], 0, 1) is [1, 2, 3].
Each item is a 32-bit signed integer. The index must be from 0 to len(items). The solutions show the in-place calls too, because most code adds to a list in place.
Solutions
| Language | At the end, in place | At a position, in place |
|---|---|---|
| Python | items.append(value) |
items.insert(index, value) |
| JavaScript, TypeScript | items.push(value) |
items.splice(index, 0, value) |
| Java | list.add(value) |
list.add(index, value) |
| C# | list.Add(value) |
list.Insert(index, value) |
| Go | items = append(items, value) |
items = slices.Insert(items, index, value) |
| Rust | v.push(value) |
v.insert(index, value) |
| C | realloc to one more item, then a[n] = value |
realloc, then memmove the tail |
| C++ | v.push_back(value) |
v.insert(v.begin() + index, value) |
| Bash | a+=("$value") |
a=("${a[@]:0:i}" "$value" "${a[@]:i}") |
- Python.
appenddoes "Append value to the end of the sequence"1.insertdoes "Insert value into sequence at the given index"1. The solution copies the list withlist(items)and then callsinsert, so the input does not change. - JavaScript.
pushadds at the end.splice"changes the contents of an array by removing or replacing existing elements and/or adding new elements in place"2, sosplice(index, 0, value)inserts. The solution usessliceand spread syntax to make a new array. - Java. An array cannot grow, so the solution makes an array with one more slot and copies the two parts with
System.arraycopy. For anArrayList,add(index, value)"Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices)"3. - C#. For
Insert, "If index is equal to Count, item is added to the end of List"4. The solution uses a collection expression with two ranges,[.. items[..index], value, .. items[index..]]. - Go.
slices.Insert"modifies s in place by inserting the values v... at index i, and returns the modified slice"5. So the solution clonesitemsfirst. Without the clone, the call can write into the array of the caller. - Rust.
insert"Inserts an element at position index within the vector, shifting all elements after it to the right"6.pushadds at the end. - C. The solution uses
mallocforn + 1items and copies the two parts withmemcpy. To grow an array in place, userealloc. "If ptr is NULL, the behavior is the same as calling malloc(new_size)"7, so the first call can start from a null pointer. - C++.
insertwith one value "Inserts a copy of value before pos"8, sov.end()as the position appends. - Bash. With
+=and parentheses, "new values are appended to the array beginning at one greater than the array’s maximum index"9. The solution takes the items before and after the index with${a[@]:offset:length}.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: the only valid index of an empty list is 0, and the result has one item.single-frontandsingle-end: a list of one item has two valid positions, 0 and 1.front-of-manyandend-of-many: the index 0 and the indexlen(items)are the two ends. The indexlen(items)is valid, but it is not a valid index for reading an item.duplicates: the value can be equal to items in the list. The result keeps all of them.limit: the items and the value can be the largest and the smallest 32-bit signed integers.- An index past the end is out of range. Each solution reports it: an exception, a panic,
NULLin C, or status 1 in Bash. Pythoninsertdoes not fail, because it works like a slice assignment, and for a slice, "If i or j is greater than len(s), use len(s)"10. So the Python solution checks the index first.
Pitfalls
- Python append returns None. "methods like insert, remove or sort that only modify the list have no return value printed"11, because "they return the default None"11. So
items = items.append(3)setsitemstoNone. Also,appendadds one item, so the append of a list adds the list as one item. Useextendto add each item:
items = [1, 2]
result = items.append(3)
print(result, items)
items.append([4, 5])
print(items, len(items))
items.extend([6, 7])
print(items, len(items))
None [1, 2, 3]
[1, 2, 3, [4, 5]] 4
[1, 2, 3, [4, 5], 6, 7] 6
- JavaScript push returns the new length. The return value is "The new length property of the object upon which the method was called"12. So
items = items.push(3)setsitemsto a number:
let items = [1, 2];
items = items.push(3);
console.log(items, typeof items);
const list = [1, 3];
list.splice(1, 0, 2);
console.log(list);
3 number
[ 1, 2, 3 ]
- Java add at a position past the end throws.
add(index, value)throwsIndexOutOfBoundsException"if the index is out of range (index < 0 || index > size())"3. The indexsize()is valid and appends:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2));
list.add(2, 3);
System.out.println(list);
try {
list.add(5, 9);
} catch (IndexOutOfBoundsException e) {
System.out.println("IndexOutOfBoundsException");
}
System.out.println(list);
}
}
[1, 2, 3]
IndexOutOfBoundsException
[1, 2, 3]
- C# Add in a foreach loop over the same list throws. "If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and the next call to MoveNext or IEnumerator.Reset throws an InvalidOperationException"13. In the example, the first
Addworks, and the loop stops at the next step. Loop over a copy, or loop with an index up to the old count:
var list = new List<int> { 1, 2 };
try
{
foreach (var x in list)
{
list.Add(x * 10);
}
}
catch (InvalidOperationException)
{
Console.WriteLine("InvalidOperationException");
}
Console.WriteLine(string.Join(",", list));
foreach (var x in list.ToList())
{
list.Add(x * 10);
}
Console.WriteLine(string.Join(",", list));
InvalidOperationException
1,2,10
1,2,10,10,20,100
- Go append in a function does not change the length of the caller.
append"returns the resulting slice"14, and a function gets a copy of the slice header. In the example,addwrites 1 into the shared array, butsinmainstill has length 0. Return the new slice, and assign it:
package main
import "fmt"
func add(s []int, v int) {
s = append(s, v)
}
func addAndReturn(s []int, v int) []int {
return append(s, v)
}
func main() {
s := make([]int, 0, 4)
add(s, 1)
fmt.Println(len(s), s, s[:1])
s = addAndReturn(s, 2)
fmt.Println(len(s), s)
}
0 [] [1]
1 [2]
- Rust insert past the end panics. For
insert, the documentation says "Panics if index > len"6. The indexlenis valid and appends. The example sets an empty panic hook, so the panic message does not go to the standard error stream:
use std::panic;
fn main() {
let mut v = vec![1, 2];
v.insert(2, 3);
println!("{v:?}");
panic::set_hook(Box::new(|_| {}));
let r = panic::catch_unwind(|| {
let mut w = vec![1, 2];
w.insert(5, 9);
});
println!("{}", if r.is_err() { "panic" } else { "no panic" });
}
[1, 2, 3]
panic
- C p = realloc(p, size) loses the array when realloc fails. "On failure, returns a null pointer. The original pointer ptr remains valid and may need to be deallocated with free or realloc"7. If the code assigns the result to
pat once, a failure setsptoNULL, and the old array leaks. Keep the result in a second pointer first. The example grows the capacity by doubling:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a = NULL;
size_t len = 0;
size_t cap = 0;
for (int x = 1; x <= 5; x++) {
if (len == cap) {
size_t ncap = cap > 0 ? cap * 2 : 2;
int *tmp = realloc(a, ncap * sizeof *a);
if (tmp == NULL) {
free(a);
return 1;
}
a = tmp;
cap = ncap;
}
a[len++] = x;
}
for (size_t i = 0; i < len; i++) {
printf("%d ", a[i]);
}
printf("len=%zu cap=%zu\n", len, cap);
free(a);
return 0;
}
1 2 3 4 5 len=5 cap=8
- C++ push_back can move all the items. "If after the operation the new size() is greater than old capacity() a reallocation takes place, in which case all iterators (including the end() iterator) and all references to the elements are invalidated"15. So a pointer or a reference to an item is not safe after
push_back. Keep an index instead. The example fills the vector to its capacity, then adds one more item:
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v{1, 2};
while (v.size() < v.capacity()) {
v.push_back(0);
}
const auto before = reinterpret_cast<std::uintptr_t>(v.data());
const std::size_t cap = v.capacity();
v.push_back(3);
const auto after = reinterpret_cast<std::uintptr_t>(v.data());
std::cout << std::boolalpha << "capacity grew: " << (v.capacity() > cap) << ", data moved: " << (before != after) << "\n";
const std::size_t first = 0;
std::cout << v[first] << "\n";
}
capacity grew: true, data moved: true
1
- Bash a+=x without parentheses changes the first item. "Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0"9. And for
+=, "When applied to a string-valued variable, value is expanded and appended to the variable’s value"9. Soa+=threeadds text toa[0], and the array keeps 2 items. Usea+=(three):
a=(one two)
a+=three
echo "${#a[@]} ${a[0]}"
b=(one two)
b+=(three)
echo "${#b[@]} ${b[2]}"
2 onethree
3 three
Related tasks
- Concatenate two lists: add all the items of a second list.
- Create an array: make an array of a given length.
- Get the length of an array: get the number of items.
- Filter a list: keep the items that pass a test.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-list/.
def insert_at(items: list[int], index: int, value: int) -> list[int]:
"""Return a new list with value at position index. index len(items) appends."""
if not 0 <= index <= len(items):
# list.insert would not fail here: it clamps the index.
raise IndexError(index)
out = list(items)
out.insert(index, value)
return out
test_insert_at.py 32 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-list/.
import pytest
from insert_at import insert_at
CASES = {
"at-end": ([1, 2], 2, 3, [1, 2, 3]),
"at-front": ([2, 3], 0, 1, [1, 2, 3]),
"in-middle": ([1, 3], 1, 2, [1, 2, 3]),
"empty": ([], 0, 7, [7]),
"single-front": ([5], 0, 4, [4, 5]),
"single-end": ([5], 1, 6, [5, 6]),
"end-of-many": ([1, 2, 3, 4], 4, 5, [1, 2, 3, 4, 5]),
"front-of-many": ([1, 2, 3, 4], 0, 0, [0, 1, 2, 3, 4]),
"duplicates": ([1, 1], 1, 1, [1, 1, 1]),
"limit": ([2147483647], 1, -2147483648, [2147483647, -2147483648]),
}
@pytest.mark.parametrize("name", CASES)
def test_insert_at(name):
items, index, value, want = CASES[name]
items0 = list(items)
assert insert_at(items, index, value) == want
assert items == items0
def test_index_past_the_end():
with pytest.raises(IndexError):
insert_at([1, 2], 3, 9)
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
#include "insert_at.hpp"
#include <cstddef>
#include <span>
#include <stdexcept>
#include <vector>
std::vector<int> insert_at(std::span<const int> items, std::size_t index, int value) {
if (index > items.size()) {
throw std::out_of_range("insert_at: index is past the end");
}
std::vector<int> out;
out.reserve(items.size() + 1);
out.assign(items.begin(), items.end());
// insert puts the value before the position, so out.end() appends.
out.insert(out.begin() + static_cast<std::ptrdiff_t>(index), value);
return out;
}
insert_at.hpp 12 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
#pragma once
#include <cstddef>
#include <span>
#include <vector>
// insert_at returns a new vector with value at position index. index
// items.size() appends. It throws std::out_of_range when index > items.size().
std::vector<int> insert_at(std::span<const int> items, std::size_t index, int value);
test_insert_at.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
#include "insert_at.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 index, int value, const std::vector<int> &want) {
if (insert_at(items, index, value) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("at-end", std::vector<int>{1, 2}, 2, 3, std::vector<int>{1, 2, 3});
check("at-front", std::vector<int>{2, 3}, 0, 1, std::vector<int>{1, 2, 3});
check("in-middle", std::vector<int>{1, 3}, 1, 2, std::vector<int>{1, 2, 3});
check("empty", std::vector<int>{}, 0, 7, std::vector<int>{7});
check("single-front", std::vector<int>{5}, 0, 4, std::vector<int>{4, 5});
check("single-end", std::vector<int>{5}, 1, 6, std::vector<int>{5, 6});
check("end-of-many", std::vector<int>{1, 2, 3, 4}, 4, 5, std::vector<int>{1, 2, 3, 4, 5});
check("front-of-many", std::vector<int>{1, 2, 3, 4}, 0, 0, std::vector<int>{0, 1, 2, 3, 4});
check("duplicates", std::vector<int>{1, 1}, 1, 1, std::vector<int>{1, 1, 1});
check("limit", std::vector<int>{INT_MAX}, 1, INT_MIN, std::vector<int>{INT_MAX, INT_MIN});
try {
const std::vector<int> two{1, 2};
insert_at(two, 3, 9);
std::cerr << "case index-past-the-end failed\n";
failures++;
} catch (const std::out_of_range &) {
}
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
final class InsertAt {
private InsertAt() {}
/** Returns a new array with value at position index. index items.length appends. */
static int[] insertAt(int[] items, int index, int value) {
if (index < 0 || index > items.length) {
throw new IndexOutOfBoundsException(index);
}
// An array cannot grow, so make one with one more slot and copy the two parts.
// For an ArrayList, list.add(index, value) does the same in place.
int[] out = new int[items.length + 1];
System.arraycopy(items, 0, out, 0, index);
out[index] = value;
System.arraycopy(items, index, out, index + 1, items.length - index);
return out;
}
}
InsertAtTest.java 40 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-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 InsertAtTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("at-end", new int[] {1, 2}, 2, 3, new int[] {1, 2, 3}),
Arguments.of("at-front", new int[] {2, 3}, 0, 1, new int[] {1, 2, 3}),
Arguments.of("in-middle", new int[] {1, 3}, 1, 2, new int[] {1, 2, 3}),
Arguments.of("empty", new int[] {}, 0, 7, new int[] {7}),
Arguments.of("single-front", new int[] {5}, 0, 4, new int[] {4, 5}),
Arguments.of("single-end", new int[] {5}, 1, 6, new int[] {5, 6}),
Arguments.of("end-of-many", new int[] {1, 2, 3, 4}, 4, 5, new int[] {1, 2, 3, 4, 5}),
Arguments.of("front-of-many", new int[] {1, 2, 3, 4}, 0, 0, new int[] {0, 1, 2, 3, 4}),
Arguments.of("duplicates", new int[] {1, 1}, 1, 1, new int[] {1, 1, 1}),
Arguments.of("limit", new int[] {2147483647}, 1, Integer.MIN_VALUE, new int[] {2147483647, Integer.MIN_VALUE}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void insertAt(String name, int[] items, int index, int value, int[] want) {
int[] items0 = items.clone();
assertArrayEquals(want, InsertAt.insertAt(items, index, value));
assertArrayEquals(items0, items);
}
@Test
void indexPastTheEnd() {
assertThrows(IndexOutOfBoundsException.class, () -> InsertAt.insertAt(new int[] {1, 2}, 3, 9));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
#include "insert_at.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
int *insert_at(const int *items, size_t n, size_t index, int value) {
if (index > n || n >= SIZE_MAX / sizeof(int)) {
return NULL;
}
int *out = malloc((n + 1) * sizeof *out);
if (out == NULL) {
return NULL;
}
// memcpy counts bytes, so multiply the counts by the item size.
if (index > 0) {
memcpy(out, items, index * sizeof *items);
}
out[index] = value;
if (n > index) {
memcpy(out + index + 1, items + index, (n - index) * sizeof *items);
}
return out;
}
insert_at.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
#ifndef INSERT_AT_H
#define INSERT_AT_H
#include <stddef.h>
// insert_at returns a new array of n + 1 items: the n items of items with
// value at position index. index n appends. The caller must free the result.
// It returns NULL when index > n or when the allocation fails.
int *insert_at(const int *items, size_t n, size_t index, int value);
#endif
test_insert_at.c 55 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
#include "insert_at.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 index, int value, const int *want) {
int *out = insert_at(items, n, index, value);
if (out == NULL || memcmp(out, want, (n + 1) * 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, index, value, want) \
do { \
const int x[] = items; \
const int w[] = want; \
check(name, x, n, index, value, w); \
} while (0)
int main(void) {
CHECK("at-end", 2, L(1, 2), 2, 3, L(1, 2, 3));
CHECK("at-front", 2, L(2, 3), 0, 1, L(1, 2, 3));
CHECK("in-middle", 2, L(1, 3), 1, 2, L(1, 2, 3));
CHECK("empty", 0, L(0), 0, 7, L(7));
CHECK("single-front", 1, L(5), 0, 4, L(4, 5));
CHECK("single-end", 1, L(5), 1, 6, L(5, 6));
CHECK("end-of-many", 4, L(1, 2, 3, 4), 4, 5, L(1, 2, 3, 4, 5));
CHECK("front-of-many", 4, L(1, 2, 3, 4), 0, 0, L(0, 1, 2, 3, 4));
CHECK("duplicates", 2, L(1, 1), 1, 1, L(1, 1, 1));
CHECK("limit", 1, L(INT_MAX), 1, INT_MIN, L(INT_MAX, INT_MIN));
const int two[] = {1, 2};
int *bad = insert_at(two, 2, 3, 9);
if (bad != NULL) {
fprintf(stderr, "case index-past-the-end failed\n");
free(bad);
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
public static class AppendToList
{
// Returns a new array with value at position index. index items.Length appends.
// The range items[..index] throws ArgumentOutOfRangeException for a bad index.
// For a List<T>, list.Insert(index, value) does the same in place.
public static int[] InsertAt(int[] items, int index, int value) =>
[.. items[..index], value, .. items[index..]];
}
AppendToListTests.cs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
using Xunit;
public sealed class AppendToListTests
{
public static TheoryData<string, int[], int, int, int[]> Cases => new()
{
{ "at-end", new int[] { 1, 2 }, 2, 3, new int[] { 1, 2, 3 } },
{ "at-front", new int[] { 2, 3 }, 0, 1, new int[] { 1, 2, 3 } },
{ "in-middle", new int[] { 1, 3 }, 1, 2, new int[] { 1, 2, 3 } },
{ "empty", new int[0], 0, 7, new int[] { 7 } },
{ "single-front", new int[] { 5 }, 0, 4, new int[] { 4, 5 } },
{ "single-end", new int[] { 5 }, 1, 6, new int[] { 5, 6 } },
{ "end-of-many", new int[] { 1, 2, 3, 4 }, 4, 5, new int[] { 1, 2, 3, 4, 5 } },
{ "front-of-many", new int[] { 1, 2, 3, 4 }, 0, 0, new int[] { 0, 1, 2, 3, 4 } },
{ "duplicates", new int[] { 1, 1 }, 1, 1, new int[] { 1, 1, 1 } },
{ "limit", new int[] { 2147483647 }, 1, int.MinValue, new int[] { 2147483647, int.MinValue } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, int[] items, int index, int value, int[] want)
{
Assert.NotNull(name);
var items0 = (int[])items.Clone();
Assert.Equal(want, AppendToList.InsertAt(items, index, value));
Assert.Equal(items0, items);
}
[Fact]
public void IndexPastTheEnd()
{
Assert.Throws<ArgumentOutOfRangeException>(() => AppendToList.InsertAt([1, 2], 3, 9));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
/**
* Returns a new array with value at position index. index items.length appends.
* @param {number[]} items
* @param {number} index
* @param {number} value
* @returns {number[]}
*/
export function insertAt(items, index, value) {
if (!Number.isInteger(index) || index < 0 || index > items.length) {
throw new RangeError(`index ${index} is out of range`);
}
// slice copies, so items does not change. splice would change it in place.
return [...items.slice(0, index), value, ...items.slice(index)];
}
insert_at.test.js 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { insertAt } from "./insert_at.js";
const cases = [
["at-end", [1, 2], 2, 3, [1, 2, 3]],
["at-front", [2, 3], 0, 1, [1, 2, 3]],
["in-middle", [1, 3], 1, 2, [1, 2, 3]],
["empty", [], 0, 7, [7]],
["single-front", [5], 0, 4, [4, 5]],
["single-end", [5], 1, 6, [5, 6]],
["end-of-many", [1, 2, 3, 4], 4, 5, [1, 2, 3, 4, 5]],
["front-of-many", [1, 2, 3, 4], 0, 0, [0, 1, 2, 3, 4]],
["duplicates", [1, 1], 1, 1, [1, 1, 1]],
["limit", [2147483647], 1, -2147483648, [2147483647, -2147483648]],
];
for (const [name, items, index, value, want] of cases) {
test(name, () => {
const items0 = [...items];
assert.deepEqual(insertAt(items, index, value), want);
assert.deepEqual(items, items0);
});
}
test("index past the end", () => {
assert.throws(() => insertAt([1, 2], 3, 9), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
export function insertAt(items: readonly number[], index: number, value: number): number[] {
if (!Number.isInteger(index) || index < 0 || index > items.length) {
throw new RangeError(`index ${index} is out of range`);
}
// slice copies, so items does not change. splice would change it in place.
return [...items.slice(0, index), value, ...items.slice(index)];
}
insert_at.test.ts 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { insertAt } from "./insert_at.ts";
const cases: [string, number[], number, number, number[]][] = [
["at-end", [1, 2], 2, 3, [1, 2, 3]],
["at-front", [2, 3], 0, 1, [1, 2, 3]],
["in-middle", [1, 3], 1, 2, [1, 2, 3]],
["empty", [], 0, 7, [7]],
["single-front", [5], 0, 4, [4, 5]],
["single-end", [5], 1, 6, [5, 6]],
["end-of-many", [1, 2, 3, 4], 4, 5, [1, 2, 3, 4, 5]],
["front-of-many", [1, 2, 3, 4], 0, 0, [0, 1, 2, 3, 4]],
["duplicates", [1, 1], 1, 1, [1, 1, 1]],
["limit", [2147483647], 1, -2147483648, [2147483647, -2147483648]],
];
for (const [name, items, index, value, want] of cases) {
test(name, () => {
const items0 = [...items];
assert.deepEqual(insertAt(items, index, value), want);
assert.deepEqual(items, items0);
});
}
test("index past the end", () => {
assert.throws(() => insertAt([1, 2], 3, 9), RangeError);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
// Package appendtolist adds one item to a slice.
package appendtolist
import "slices"
// InsertAt returns a new slice with value at position index. index len(items)
// appends. slices.Insert changes the array of its argument when it has room,
// so InsertAt clones items first. It panics if index is out of range.
func InsertAt(items []int, index, value int) []int {
return slices.Insert(slices.Clone(items), index, value)
}
insert_at_test.go 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
package appendtolist
import (
"slices"
"testing"
)
var cases = []struct {
name string
items []int
index, value int
want []int
}{
{"at-end", []int{1, 2}, 2, 3, []int{1, 2, 3}},
{"at-front", []int{2, 3}, 0, 1, []int{1, 2, 3}},
{"in-middle", []int{1, 3}, 1, 2, []int{1, 2, 3}},
{"empty", []int{}, 0, 7, []int{7}},
{"single-front", []int{5}, 0, 4, []int{4, 5}},
{"single-end", []int{5}, 1, 6, []int{5, 6}},
{"end-of-many", []int{1, 2, 3, 4}, 4, 5, []int{1, 2, 3, 4, 5}},
{"front-of-many", []int{1, 2, 3, 4}, 0, 0, []int{0, 1, 2, 3, 4}},
{"duplicates", []int{1, 1}, 1, 1, []int{1, 1, 1}},
{"limit", []int{2147483647}, 1, -2147483648, []int{2147483647, -2147483648}},
}
func TestInsertAt(t *testing.T) {
for _, c := range cases {
items0 := slices.Clone(c.items)
if got := InsertAt(c.items, c.index, c.value); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
if !slices.Equal(c.items, items0) {
t.Errorf("%s: the input changed", c.name)
}
}
// The input must not change, even when its array has room.
items := make([]int, 2, 4)
InsertAt(items, 0, 9)
if items[:3][0] != 0 || items[:3][2] != 0 {
t.Errorf("the array of the input changed: %v", items[:3])
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
/// Returns a new vector with value at position index. index items.len() appends.
///
/// # Panics
///
/// Panics if index > items.len(), as Vec::insert does.
pub fn insert_at(items: &[i32], index: usize, value: i32) -> Vec<i32> {
let mut out = Vec::with_capacity(items.len() + 1);
out.extend_from_slice(items);
out.insert(index, value);
out
}
tests/insert_at_test.rs 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/append-to-a-list/.
use algo_append_to_a_list::insert_at;
#[test]
fn cases() {
let cases: &[(&str, &[i32], usize, i32, &[i32])] = &[
("at-end", &[1, 2], 2, 3, &[1, 2, 3]),
("at-front", &[2, 3], 0, 1, &[1, 2, 3]),
("in-middle", &[1, 3], 1, 2, &[1, 2, 3]),
("empty", &[], 0, 7, &[7]),
("single-front", &[5], 0, 4, &[4, 5]),
("single-end", &[5], 1, 6, &[5, 6]),
("end-of-many", &[1, 2, 3, 4], 4, 5, &[1, 2, 3, 4, 5]),
("front-of-many", &[1, 2, 3, 4], 0, 0, &[0, 1, 2, 3, 4]),
("duplicates", &[1, 1], 1, 1, &[1, 1, 1]),
("limit", &[2147483647], 1, i32::MIN, &[2147483647, i32::MIN]),
];
for &(name, items, index, value, want) in cases {
assert_eq!(insert_at(items, index, value), want, "{name}");
}
}
#[test]
#[should_panic]
fn index_past_the_end() {
insert_at(&[1, 2], 3, 9);
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-list/.
# insert_at NAME INDEX VALUE
# Prints the items of the array NAME with VALUE at position INDEX, one on each
# line. INDEX equal to the number of items appends. It returns 1 when INDEX is
# out of range. The name is passed, because a function cannot take an array
# as one argument.
insert_at() {
local -n _insert_at_items=$1
local index=$2
if ! [[ $index =~ ^[0-9]+$ ]] || ((index > ${#_insert_at_items[@]})); then
return 1
fi
# ${a[@]:i:n} takes n items from position i. The quotes keep each item one word.
local -a _insert_at_out=("${_insert_at_items[@]:0:index}" "$3" "${_insert_at_items[@]:index}")
printf '%s\n' "${_insert_at_out[@]}"
}
test_insert_at.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/append-to-a-list/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/insert_at.sh"
}
check() { # check "ITEMS" INDEX VALUE -- WANT...
local -a items
read -r -a items <<<"$1"
local index=$2 value=$3
shift 4
local got want
# The x keeps the trailing newlines, which $(...) removes.
got=$(insert_at items "$index" "$value"; printf x)
want=$(printf '%s\n' "$@"; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "at-end" { check "1 2" 2 3 -- 1 2 3; }
@test "at-front" { check "2 3" 0 1 -- 1 2 3; }
@test "in-middle" { check "1 3" 1 2 -- 1 2 3; }
@test "empty" { check "" 0 7 -- 7; }
@test "single-front" { check "5" 0 4 -- 4 5; }
@test "single-end" { check "5" 1 6 -- 5 6; }
@test "end-of-many" { check "1 2 3 4" 4 5 -- 1 2 3 4 5; }
@test "front-of-many" { check "1 2 3 4" 0 0 -- 0 1 2 3 4; }
@test "duplicates" { check "1 1" 1 1 -- 1 1 1; }
@test "limit" { check "2147483647" 1 -2147483648 -- 2147483647 -2147483648; }
@test "spaces" { local -a x=("New York" Rome); got=$(insert_at x 1 Paris; printf x); [ "$got" = $'New York\nParis\nRome\nx' ]; }
@test "past-the-end" { local -a x=(1 2); if insert_at x 3 9 >/dev/null; then return 1; fi; }
References
- The Python Standard Library, Built-in Types, Mutable Sequence Types, sequence.append and sequence.insert
- MDN Web Docs, Array.prototype.splice(), Description
- Java SE 25 API, Class ArrayList, add(int index, E element)
- .NET API reference, List<T>.Insert method, Remarks and Exceptions
- Go standard library, package slices, func Insert
- Rust standard library, struct Vec, insert
- cppreference.com, realloc, Description and Return value
- cppreference.com, std::vector::insert, Description
- Bash Reference Manual, 3.4 Shell Parameters and 6.7 Arrays
- The Python Standard Library, Built-in Types, Common Sequence Operations, note 4
- The Python Tutorial, Data Structures, 5.1 More on Lists
- MDN Web Docs, Array.prototype.push(), Return value
- .NET API reference, List<T>.GetEnumerator method, Remarks
- The Go Programming Language Specification, Appending to and copying slices
- cppreference.com, std::vector::push_back, 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 8R8Q8H Edit this page History Report an error Markdown