Programming Search⌘K

Taskintro

Check whether a list contains a value

Also called list contains, array includes, membership test, in operator, value in list, linear search, find an item in a list, includes.

Tell whether a value is one of the items of a list, and know which equality each language uses, how NaN and object items behave, and when a set is the better structure.

Task

Tell whether a value is in a list. The function contains(items, value) returns true if some item of items is equal to value, and false if not. For example, contains([1, 2, 3], 2) is true, and contains([1, 2, 3], 4) is false.

The function must not change items. Each item and the value are 32-bit signed integers, and the list has 0 to 1000 items.

Solutions

Language Contains Equality used
Python value in items is, then ==
JavaScript, TypeScript items.includes(value) SameValueZero
Java Arrays.stream(items).anyMatch(x -> x == value), list.contains(value) == for int, Objects.equals for a List
C# Array.IndexOf(items, value) >= 0, list.Contains(value) EqualityComparer<T>.Default
Go slices.Contains(items, value) ==
Rust items.contains(&value) PartialEq
C a loop with == ==, or strcmp for strings
C++ std::ranges::contains(items, value) ==
Bash a loop with [[ $item == "$value" ]] string equality
  • Python. "For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression x in y is equivalent to any(x is e or x == e for e in y)"1.
  • JavaScript. "The includes() method compares searchElement to elements of the array using the SameValueZero algorithm"2. TypeScript uses the same method on a readonly number[].
  • Java. List.contains returns true "if and only if this list contains at least one element e such that Objects.equals(o, e)"3. The input is an int[], so the solution uses a stream of int.
  • C#. List<T>.Contains "determines equality using the default equality comparer EqualityComparer.Default for T"4, and "This method performs a linear search"4. The solution uses Array.IndexOf on the array.
  • Go. "Contains reports whether v is present in s"5. The item type must be comparable. For other tests, slices.ContainsFunc takes a function.
  • Rust. contains takes a reference to the value, as in items.contains(&value)6.
  • C. C has no contains function for an int array. The solution compares each item with == and returns at the first match.
  • C++. std::ranges::contains "Checks whether or not the source range contains the target value value"7. With an older standard library, compare the result of std::find with the end: std::find returns "an iterator to the first element in the source range [first, last) that satisfies specific criteria (or last if there is no such iterator)"8.
  • Bash. For [[ ... == ... ]], "the string to the right of the operator is considered a pattern"9. The solution puts the value in double quotes, so the right side is a string. The function returns the status 0 for found and 1 for not found, so a caller can use it as the test of an if.

Each solution is a linear search: it compares the value with the items in order, so it takes time in proportion to the length of the list. A program that tests many values against one list can put the items in a set once, and then each test takes about the same time for any size.

Edge cases

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

  • empty: an empty list contains no value, so the result is false.
  • single-yes and single-no: a list of one item.
  • first and last: the value at the first and at the last position. A loop with a bound off by one misses one of them.
  • duplicates: the value can be in the list more than once, and the result is still true.
  • negative and zero-absent: negative items, and 0 when the list has no 0. A test that uses a position as a truth value fails here.
  • limit and limit-absent: the smallest 32-bit integer is found in a list that has it, and is not found in a list that has only the largest.
  • Each test checks that items does not change. The task find the index of a value also gives the position.

Pitfalls

  • Python in tests identity before equality. Because x in y is any(x is e or x == e for e in y)1, a NaN object is found in a list that holds the same object, though nan == nan is false. A different NaN object is not found. Also, True == 1 in Python, so True in [1] is true:
nan = float("nan")
print(nan == nan, nan in [nan], float("nan") in [nan])
print(True in [1], 1.0 in [1])
Output
False True False
True True
  • JavaScript indexOf does not find NaN, and 0 is falsy. SameValueZero works "like strict equality === (where -0 and +0 are considered equal), with the exception that NaN is considered equal to itself"2. But for indexOf, "NaN values are never compared as equal, so indexOf() always returns -1 when searchElement is NaN"10. Also, if (a.indexOf(x)) is false when x is the first item, because the position 0 is falsy. Use includes for a yes or no answer:
const a = [1, NaN];
console.log(a.includes(NaN), a.indexOf(NaN));
console.log(a.indexOf(1) ? "found" : "not found");
console.log(a.includes(1) ? "found" : "not found");
Output
true -1
not found
found
  • Java Arrays.asList of an int[] is a list of one array. asList(T... a) "Returns a fixed-size list backed by the specified array"11, but T cannot be int. So Arrays.asList(new int[] {1, 2, 3}) is a List<int[]> with one item, and contains(1) is false. Also, contains uses Objects.equals3, and an Integer is never equal to a Long, so List.of(1L).contains(1) is false:
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    int[] a = {1, 2, 3};
    System.out.println(Arrays.asList(a).contains(1) + " " + Arrays.asList(a).size());
    System.out.println(Arrays.stream(a).anyMatch(x -> x == 1));
    List<Long> b = List.of(1L, 2L);
    System.out.println(b.contains(1) + " " + b.contains(1L));
  }
}
Output
false 1
true
false true
  • C# Contains compares class objects by reference. Contains uses the default equality comparer4. "For class types, two objects are equal if they refer to the same object in memory"12, unless the class overrides Equals. A record has value equality. So a new object with the same fields is not found in a list of a class, but it is found in a list of a record:
var classes = new List<PointClass> { new() { X = 1, Y = 2 } };
var records = new List<PointRecord> { new(1, 2) };
Console.WriteLine(classes.Contains(new PointClass { X = 1, Y = 2 }));
Console.WriteLine(records.Contains(new PointRecord(1, 2)));

class PointClass
{
    public int X { get; init; }
    public int Y { get; init; }
}

record PointRecord(int X, int Y);
Output
False
True
  • Go slices.Contains does not find NaN. Contains uses ==, and "Two floating-point values are compared as defined by the IEEE 754 standard"13. In IEEE 754, NaN is not equal to any value, NaN too. Use slices.ContainsFunc5 with math.IsNaN:
package main

import (
	"fmt"
	"math"
	"slices"
)

func main() {
	a := []float64{1, math.NaN()}
	fmt.Println(slices.Contains(a, math.NaN()))
	fmt.Println(slices.ContainsFunc(a, math.IsNaN))
}
Output
false
true
  • Rust contains needs a &T, so a &str does not work on a Vec<String>. A call such as v.contains(&s) with a &str named s does not compile, because the item type is String. "If you do not have a &T, but some other value that you can compare with one (for example, String implements PartialEq), you can use iter().any"6:
fn main() {
    let v = vec![String::from("a"), String::from("b")];
    println!("{}", v.contains(&String::from("b")));
    println!("{}", v.iter().any(|s| s == "b"));
}
Output
true
true
  • C == on strings compares the pointers. Two arrays with the same characters are at different addresses, so == is false. strcmp returns "Zero if lhs and rhs compare equal"14:
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *names[] = {"ann", "bob"};
    char want[] = "bob";
    bool by_pointer = false;
    bool by_text = false;
    for (size_t i = 0; i < 2; i++) {
        if (names[i] == want) {
            by_pointer = true;
        }
        if (strcmp(names[i], want) == 0) {
            by_text = true;
        }
    }
    printf("%d %d\n", by_pointer, by_text);
    return 0;
}
Output
0 1
  • C++ std::binary_search needs a sorted range. It "Checks if an element equivalent to value exists in the partitioned source range [first, last)"15, and the behavior is undefined if the range is not partitioned15. On an unsorted vector, it can miss an item that is there. Sort the vector first, or use std::ranges::contains. The output is from the GCC library:
#include <algorithm>
#include <iostream>
#include <vector>

int main() {
    std::vector<int> v{5, 1, 4, 2, 3};
    std::cout << std::ranges::contains(v, 1) << " " << std::binary_search(v.begin(), v.end(), 1) << "\n";
    std::ranges::sort(v);
    std::cout << std::binary_search(v.begin(), v.end(), 1) << "\n";
}
Output
1 0
1
  • Bash an unquoted right side is a pattern, and a joined string finds parts of items. The right side of == is a pattern9, so with x='*', [[ $item == $x ]] is true for each item. A test on the joined list, [[ " ${a[*]} " == *" $x "* ]], finds York in the item New York. Loop over the items and quote the value:
a=("New York" Paris)
x='*'
for item in "${a[@]}"; do
  if [[ $item == $x ]]; then echo "unquoted: $item"; fi
  if [[ $item == "$x" ]]; then echo "quoted: $item"; fi
done
x=York
if [[ " ${a[*]} " == *" $x "* ]]; then echo "joined: found"; fi
Output
unquoted: New York
unquoted: Paris
joined: found

Code

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

contains.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

def contains(items: list[int], value: int) -> bool:
    """Return True if some item of items is equal to value."""
    # in compares each item with value, so it takes time in proportion to len(items).
    return value in items
test_contains.py 29 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

import pytest

from contains import contains

CASES = {
    "present": ([1, 2, 3], 2, True),
    "absent": ([1, 2, 3], 4, False),
    "empty": ([], 0, False),
    "single-yes": ([5], 5, True),
    "single-no": ([5], 0, False),
    "first": ([7, 8, 9], 7, True),
    "last": ([7, 8, 9], 9, True),
    "duplicates": ([2, 2, 2], 2, True),
    "negative": ([-1, -2, -3], -2, True),
    "zero-absent": ([-1, 1], 0, False),
    "limit": ([2147483647, -2147483648], -2147483648, True),
    "limit-absent": ([2147483647], -2147483648, False),
}


@pytest.mark.parametrize("name", CASES)
def test_contains(name):
    items, value, want = CASES[name]
    items0 = list(items)
    assert contains(items, value) is want
    assert items == items0
contains.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

#include "contains.hpp"

#include <algorithm>
#include <span>

bool contains(std::span<const int> items, int value) {
    // std::ranges::contains is new in C++23. Before it, compare
    // std::find(first, last, value) with last.
    return std::ranges::contains(items, value);
}
contains.hpp 9 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

#pragma once

#include <span>

// contains returns true if some item of items is equal to value.
bool contains(std::span<const int> items, int value);
test_contains.cpp 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

#include "contains.hpp"

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

static int failures = 0;

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

int main() {
    check("present", std::vector<int>{1, 2, 3}, 2, true);
    check("absent", std::vector<int>{1, 2, 3}, 4, false);
    check("empty", std::vector<int>{}, 0, false);
    check("single-yes", std::vector<int>{5}, 5, true);
    check("single-no", std::vector<int>{5}, 0, false);
    check("first", std::vector<int>{7, 8, 9}, 7, true);
    check("last", std::vector<int>{7, 8, 9}, 9, true);
    check("duplicates", std::vector<int>{2, 2, 2}, 2, true);
    check("negative", std::vector<int>{-1, -2, -3}, -2, true);
    check("zero-absent", std::vector<int>{-1, 1}, 0, false);
    check("limit", std::vector<int>{INT_MAX, INT_MIN}, INT_MIN, true);
    check("limit-absent", std::vector<int>{INT_MAX}, INT_MIN, false);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Contains.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

import java.util.Arrays;

final class Contains {
  private Contains() {}

  /** Returns true if some item of items is equal to value. */
  static boolean contains(int[] items, int value) {
    // Arrays.asList(items) would be a List<int[]> with one item, so use a stream of int.
    return Arrays.stream(items).anyMatch(x -> x == value);
  }
}
ContainsTest.java 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

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

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 ContainsTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("present", new int[] {1, 2, 3}, 2, true),
        Arguments.of("absent", new int[] {1, 2, 3}, 4, false),
        Arguments.of("empty", new int[] {}, 0, false),
        Arguments.of("single-yes", new int[] {5}, 5, true),
        Arguments.of("single-no", new int[] {5}, 0, false),
        Arguments.of("first", new int[] {7, 8, 9}, 7, true),
        Arguments.of("last", new int[] {7, 8, 9}, 9, true),
        Arguments.of("duplicates", new int[] {2, 2, 2}, 2, true),
        Arguments.of("negative", new int[] {-1, -2, -3}, -2, true),
        Arguments.of("zero-absent", new int[] {-1, 1}, 0, false),
        Arguments.of("limit", new int[] {2147483647, Integer.MIN_VALUE}, Integer.MIN_VALUE, true),
        Arguments.of("limit-absent", new int[] {2147483647}, Integer.MIN_VALUE, false));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void contains(String name, int[] items, int value, boolean want) {
    int[] items0 = items.clone();
    assertEquals(want, Contains.contains(items, value));
    assertArrayEquals(items0, items);
  }
}
contains.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

#include "contains.h"

#include <stdbool.h>
#include <stddef.h>

bool contains(const int *items, size_t n, int value) {
    for (size_t i = 0; i < n; i++) {
        if (items[i] == value) {
            return true;
        }
    }
    return false;
}
contains.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

#ifndef CONTAINS_H
#define CONTAINS_H

#include <stdbool.h>
#include <stddef.h>

// contains returns true if one of the n items is equal to value.
bool contains(const int *items, size_t n, int value);

#endif
test_contains.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

#include "contains.h"

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

static int failures = 0;

#define L(...) {__VA_ARGS__}

// C has no empty array, so an empty list is the array {0} with a count of 0.
#define CHECK(name, n, items, value, want)              \
    do {                                                \
        const int x[] = items;                          \
        if (contains(x, n, value) != (want)) {          \
            fprintf(stderr, "case %s failed\n", name); \
            failures++;                                 \
        }                                               \
    } while (0)

int main(void) {
    CHECK("present", 3, L(1, 2, 3), 2, true);
    CHECK("absent", 3, L(1, 2, 3), 4, false);
    CHECK("empty", 0, L(0), 0, false);
    CHECK("single-yes", 1, L(5), 5, true);
    CHECK("single-no", 1, L(5), 0, false);
    CHECK("first", 3, L(7, 8, 9), 7, true);
    CHECK("last", 3, L(7, 8, 9), 9, true);
    CHECK("duplicates", 3, L(2, 2, 2), 2, true);
    CHECK("negative", 3, L(-1, -2, -3), -2, true);
    CHECK("zero-absent", 2, L(-1, 1), 0, false);
    CHECK("limit", 2, L(INT_MAX, INT_MIN), INT_MIN, true);
    CHECK("limit-absent", 1, L(INT_MAX), INT_MIN, false);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Contains.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

public static class Contains
{
    // Returns true if some item of items is equal to value. Array.IndexOf
    // compares each item with the default equality comparer of int.
    public static bool Of(int[] items, int value) => Array.IndexOf(items, value) >= 0;
}
ContainsTests.cs 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

using Xunit;

public sealed class ContainsTests
{
    public static TheoryData<string, int[], int, bool> Cases => new()
    {
        { "present", new int[] { 1, 2, 3 }, 2, true },
        { "absent", new int[] { 1, 2, 3 }, 4, false },
        { "empty", new int[0], 0, false },
        { "single-yes", new int[] { 5 }, 5, true },
        { "single-no", new int[] { 5 }, 0, false },
        { "first", new int[] { 7, 8, 9 }, 7, true },
        { "last", new int[] { 7, 8, 9 }, 9, true },
        { "duplicates", new int[] { 2, 2, 2 }, 2, true },
        { "negative", new int[] { -1, -2, -3 }, -2, true },
        { "zero-absent", new int[] { -1, 1 }, 0, false },
        { "limit", new int[] { 2147483647, int.MinValue }, int.MinValue, true },
        { "limit-absent", new int[] { 2147483647 }, int.MinValue, false },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, int[] items, int value, bool want)
    {
        Assert.NotNull(name);
        var items0 = (int[])items.Clone();
        Assert.Equal(want, Contains.Of(items, value));
        Assert.Equal(items0, items);
    }
}
contains.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

/**
 * Returns true if some item of items is equal to value.
 * @param {number[]} items
 * @param {number} value
 * @returns {boolean}
 */
export function contains(items, value) {
  // includes returns a boolean. indexOf returns a position, and 0 is falsy.
  return items.includes(value);
}
contains.test.js 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

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

import { contains } from "./contains.js";

const cases = [
  ["present", [1, 2, 3], 2, true],
  ["absent", [1, 2, 3], 4, false],
  ["empty", [], 0, false],
  ["single-yes", [5], 5, true],
  ["single-no", [5], 0, false],
  ["first", [7, 8, 9], 7, true],
  ["last", [7, 8, 9], 9, true],
  ["duplicates", [2, 2, 2], 2, true],
  ["negative", [-1, -2, -3], -2, true],
  ["zero-absent", [-1, 1], 0, false],
  ["limit", [2147483647, -2147483648], -2147483648, true],
  ["limit-absent", [2147483647], -2147483648, false],
];

for (const [name, items, value, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    assert.equal(contains(items, value), want);
    assert.deepEqual(items, items0);
  });
}
contains.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

export function contains(items: readonly number[], value: number): boolean {
  // includes returns a boolean. indexOf returns a position, and 0 is falsy.
  return items.includes(value);
}
contains.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

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

import { contains } from "./contains.ts";

const cases: [string, number[], number, boolean][] = [
  ["present", [1, 2, 3], 2, true],
  ["absent", [1, 2, 3], 4, false],
  ["empty", [], 0, false],
  ["single-yes", [5], 5, true],
  ["single-no", [5], 0, false],
  ["first", [7, 8, 9], 7, true],
  ["last", [7, 8, 9], 9, true],
  ["duplicates", [2, 2, 2], 2, true],
  ["negative", [-1, -2, -3], -2, true],
  ["zero-absent", [-1, 1], 0, false],
  ["limit", [2147483647, -2147483648], -2147483648, true],
  ["limit-absent", [2147483647], -2147483648, false],
];

for (const [name, items, value, want] of cases) {
  test(name, () => {
    const items0 = [...items];
    assert.equal(contains(items, value), want);
    assert.deepEqual(items, items0);
  });
}
contains.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

// Package contains tells whether a slice has a value.
package contains

import "slices"

// Contains reports whether some item of items is equal to value.
func Contains(items []int, value int) bool {
	return slices.Contains(items, value)
}
contains_test.go 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

package contains

import (
	"math"
	"slices"
	"testing"
)

var cases = []struct {
	name  string
	items []int
	value int
	want  bool
}{
	{"present", []int{1, 2, 3}, 2, true},
	{"absent", []int{1, 2, 3}, 4, false},
	{"empty", []int{}, 0, false},
	{"single-yes", []int{5}, 5, true},
	{"single-no", []int{5}, 0, false},
	{"first", []int{7, 8, 9}, 7, true},
	{"last", []int{7, 8, 9}, 9, true},
	{"duplicates", []int{2, 2, 2}, 2, true},
	{"negative", []int{-1, -2, -3}, -2, true},
	{"zero-absent", []int{-1, 1}, 0, false},
	{"limit", []int{2147483647, math.MinInt32}, math.MinInt32, true},
	{"limit-absent", []int{2147483647}, math.MinInt32, false},
}

func TestContains(t *testing.T) {
	for _, c := range cases {
		items0 := slices.Clone(c.items)
		if got := Contains(c.items, c.value); 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)
		}
	}
}
contains.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

/// Returns true if some item of items is equal to value.
pub fn contains(items: &[i32], value: i32) -> bool {
    // contains takes a reference to the value.
    items.contains(&value)
}
tests/contains_test.rs 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

use algo_check_whether_a_list_contains_a_value::contains;

#[test]
fn cases() {
    let cases: &[(&str, &[i32], i32, bool)] = &[
        ("present", &[1, 2, 3], 2, true),
        ("absent", &[1, 2, 3], 4, false),
        ("empty", &[], 0, false),
        ("single-yes", &[5], 5, true),
        ("single-no", &[5], 0, false),
        ("first", &[7, 8, 9], 7, true),
        ("last", &[7, 8, 9], 9, true),
        ("duplicates", &[2, 2, 2], 2, true),
        ("negative", &[-1, -2, -3], -2, true),
        ("zero-absent", &[-1, 1], 0, false),
        ("limit", &[2147483647, i32::MIN], i32::MIN, true),
        ("limit-absent", &[2147483647], i32::MIN, false),
    ];
    for &(name, items, value, want) in cases {
        assert_eq!(contains(items, value), want, "{name}");
    }
}
contains.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

# contains VALUE ITEM...
# Returns 0 if one of the items is equal to VALUE as a string, and 1 if not.
contains() {
  local value=$1 item
  shift
  for item in "$@"; do
    # The quotes make the right side a string, not a pattern.
    if [[ $item == "$value" ]]; then
      return 0
    fi
  done
  return 1
}
test_contains.bats 34 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/check-whether-a-list-contains-a-value/.

bats_require_minimum_version 1.5.0

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

check() { # check VALUE "ITEMS" WANT: WANT is yes or no
  local -a items
  read -r -a items <<<"$2"
  if contains "$1" "${items[@]}"; then
    [ "$3" = yes ]
  else
    [ "$3" = no ]
  fi
}

@test "present" { check 2 "1 2 3" yes; }
@test "absent" { check 4 "1 2 3" no; }
@test "empty" { check 0 "" no; }
@test "single-yes" { check 5 "5" yes; }
@test "single-no" { check 0 "5" no; }
@test "first" { check 7 "7 8 9" yes; }
@test "last" { check 9 "7 8 9" yes; }
@test "duplicates" { check 2 "2 2 2" yes; }
@test "negative" { check -2 "-1 -2 -3" yes; }
@test "zero-absent" { check 0 "-1 1" no; }
@test "limit" { check -2147483648 "2147483647 -2147483648" yes; }
@test "limit-absent" { check -2147483648 "2147483647" no; }
@test "pattern" { if contains "*" a b; then return 1; fi; contains "*" a "*"; }
@test "spaces" { if contains York "New York" Paris; then return 1; fi; contains "New York" "New York" Paris; }

References

  1. The Python Language Reference, Expressions, 6.10.2 Membership test operations
  2. MDN Web Docs, Array.prototype.includes(), Description
  3. Java SE 25 API, Interface List, contains(Object o)
  4. .NET API reference, List<T>.Contains(T), Remarks
  5. Go standard library, package slices, func Contains and func ContainsFunc
  6. Rust standard library, Primitive Type slice, contains
  7. cppreference.com, std::ranges::contains, Description
  8. cppreference.com, std::find, Description
  9. Bash Reference Manual, 3.2.5.2 Conditional Constructs, [[...]]
  10. MDN Web Docs, Array.prototype.indexOf(), Description
  11. Java SE 25 API, Class Arrays, asList(T... a)
  12. C# language reference, Records, Value equality
  13. The Go Programming Language Specification, Comparison operators
  14. cppreference.com, strcmp, Return value
  15. cppreference.com, std::binary_search, 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