Programming Search⌘K

Taskintro

Get the length of an array

Also called array length, array size, count the items of an array, number of elements, len, length of a list, size of a vector.

Get the number of items in an array or list with len, length, size or Count, and know why sizeof and a pointer give a wrong count in C.

Task

Get the number of items in an array of strings. The function length(items) returns the count. For example, length(["a", "b", "c"]) is 3, and length([]) is 0.

The function counts items, not characters or bytes. So length(["", ""]) is 2, and length(["é", "日本語"]) is 2.

Solutions

Language Array List or growable array
Python len(items) len(items)
JavaScript, TypeScript items.length items.length
Java items.length (a field) list.size()
C# items.Length list.Count
Go len(items) len(items)
Rust items.len() v.len()
C sizeof a / sizeof a[0] in the scope of the array a count that the code keeps
C++ std::size(a) v.size() or std::ssize(v)
Bash ${#a[@]} ${#a[@]}
  • Python. len returns "the length (the number of items) of an object"1. It works on any sequence or collection.
  • JavaScript. "The length data property of an Array instance represents the number of slots in that array"2. A slot can be empty, so the length is the number of items only for an array with no holes (see the pitfalls).
  • Java. An array has "The public final field length, which contains the number of components of the array"3. It is a field, so it has no parentheses. A String has the method length(), and a collection has size().
  • C#. For an array, Length is "The total number of elements in all the dimensions of the Array"4. A List<T> has Count.
  • Go. len works on arrays, slices, strings, maps and channels. "The length of a nil slice, map or channel is 0"5.
  • C. A function gets a pointer, not an array, so it cannot find the length with sizeof. The array must come with a count, or it must end with a marker. The solution uses a null pointer as the marker, like argv, where "the last element, argv[argc], is guaranteed to be a null pointer"6.
  • C++. std::size works on containers and on built-in arrays. For an array of N items, it "Returns N"7.
  • Bash. "If subscript is ‘@’ or ‘*’, the expansion is the number of elements in the array"8. The solution takes the items as arguments, so $# gives the count.

Edge cases

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

  • empty: an empty array has length 0.
  • single: one item gives 1.
  • empty-strings: an empty string is an item, so ["", ""] has length 2. In C, an empty string is not a null pointer, so it does not end the array.
  • non-ascii: the length counts items, not the characters or the bytes of the items.
  • duplicates and ten: equal items count once each.

Pitfalls

  • Python len does not work on a generator. len takes "a sequence (such as a string, bytes, tuple, list, or range) or a collection"1. A generator is neither, so len raises TypeError. To count its items, use the generator up, for example with sum:
squares = (x * x for x in range(3))
try:
    len(squares)
except TypeError as e:
    print(type(e).__name__)
print(sum(1 for _ in squares))
print(len([x * x for x in range(3)]))
Output
TypeError
3
3
  • JavaScript length is not the number of items in a sparse array. The length "is always numerically greater than the highest index in the array. It may be greater than the number of elements if the array is sparse"2. An assignment to a larger index "extends the array"2, and a smaller length "truncates the array"2:
const a = [];
a[9] = "x";
console.log(a.length, Object.keys(a).length);
a.length = 2;
console.log(a);
Output
10 1
[ <2 empty items> ]
  • Java Arrays.asList of an int array has one item. For generics, "you cannot substitute a primitive type for the type parameter"9. So Arrays.asList(nums) with an int[] gives a list with one item, the array itself. An Integer[] gives a list of 3 items:
import java.util.Arrays;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    int[] nums = {1, 2, 3};
    System.out.println(nums.length);
    System.out.println(Arrays.asList(nums).size());
    Integer[] boxed = {1, 2, 3};
    System.out.println(Arrays.asList(boxed).size());
    System.out.println("abc".length() + " " + List.of(1, 2).size());
  }
}
Output
3
1
3
3 2
  • C# Length of a multidimensional array counts all the items. For a 3 by 4 array, Length is 12. Use GetLength(0) for the number of rows. A jagged array is an array of arrays, so its Length is the number of rows:
int[,] grid = new int[3, 4];
Console.WriteLine($"{grid.Length} {grid.GetLength(0)} {grid.GetLength(1)}");
int[][] jagged = [new int[4], new int[2]];
Console.WriteLine($"{jagged.Length} {jagged[0].Length} {jagged[1].Length}");
Output
12 3 4
2 4 2
  • Go len is not cap. len is the number of items, and cap is the room. "For slices, the upper index bound is the slice capacity cap(a) rather than the length"10, so a slice expression can make a slice longer than the slice it starts from:
package main

import "fmt"

func main() {
	var s []int
	fmt.Println(len(s), s == nil)
	t := make([]int, 2, 10)
	fmt.Println(len(t), cap(t))
	u := t[:5]
	fmt.Println(len(u), cap(u))
}
Output
0 true
2 10
5 10
  • Rust with_capacity gives an empty vector. "It is important to note that although the returned vector has the minimum capacity specified, the vector will have a zero length"11. len counts the items, and capacity gives the room:
fn main() {
    let mut v: Vec<i32> = Vec::with_capacity(10);
    println!("{} {}", v.len(), v.capacity() >= 10);
    v.push(1);
    println!("{} {}", v.len(), v.is_empty());
    let a = [0u8; 4];
    println!("{}", a.len());
}
Output
0 true
1 false
4
  • C sizeof of a pointer is not the length. sizeof a / sizeof a[0] gives the number of items of an array. "Note that if a has pointer type (such as after array-to-pointer conversion of function parameter type adjustment), this expression would simply divide the number of bytes in a pointer type by the number of bytes in the pointed type"12. In the example, the function gets a pointer, and sizeof p is the size of the pointer. The output is from a 64-bit machine with 4-byte int:
#include <stdio.h>

static size_t bytes(const int *p) {
    return sizeof p;
}

int main(void) {
    int a[5] = {0};
    printf("%zu %zu\n", sizeof a, sizeof a / sizeof a[0]);
    printf("%zu\n", bytes(a));
    return 0;
}
Output
20 5
8
  • C++ size() is unsigned. Unsigned integer arithmetic wraps around: "subtracting one from 0 gives UINT_MAX"13 for unsigned int, and the same rule holds for std::size_t. So v.size() - 1 on an empty vector is a very large number. std::ssize returns a signed type7, so std::ssize(v) - 1 is -1:
#include <iostream>
#include <iterator>
#include <vector>

int main() {
    std::vector<int> v;
    std::cout << v.size() - 1 << "\n";
    std::cout << std::ssize(v) - 1 << "\n";
    int a[4]{};
    std::cout << std::size(a) << "\n";
}
Output
18446744073709551615
-1
4
  • Bash ${#a} is the length of the first item. "Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0"8, so ${#a} is the number of characters in ${a[0]}. Bash arrays can have gaps, so the count is not always the largest index plus one:
a=(apple banana cherry)
echo "${#a} ${#a[@]}"
b=()
b[5]=x
echo "${#b[@]} ${!b[@]}"
Output
5 3
1 5

Code

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

length.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-length-of-an-array/.

def length(items: list[str]) -> int:
    """Return the number of items in items."""
    # len works on any sequence or collection, but not on a generator.
    return len(items)
test_length.py 23 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-length-of-an-array/.

import pytest

from length import length

CASES = {
    "three": (["a", "b", "c"], 3),
    "two-words": (["apple", "banana"], 2),
    "empty": ([], 0),
    "single": (["x"], 1),
    "empty-strings": (["", ""], 2),
    "non-ascii": (["é", "日本語"], 2),
    "duplicates": (["a", "a", "a"], 3),
    "ten": (["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 10),
}


@pytest.mark.parametrize("name", CASES)
def test_length(name):
    items, want = CASES[name]
    assert length(items) == want
length.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

#include "length.hpp"

#include <cstddef>
#include <span>
#include <string>

std::size_t length(std::span<const std::string> items) {
    // size is unsigned. Use std::ssize when the code subtracts from it.
    return items.size();
}
length.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

#pragma once

#include <cstddef>
#include <span>
#include <string>

// length returns the number of items in items.
std::size_t length(std::span<const std::string> items);
test_length.cpp 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

#include "length.hpp"

#include <cstddef>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>

static int failures = 0;

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

int main() {
    check("three", std::vector<std::string>{"a", "b", "c"}, 3);
    check("two-words", std::vector<std::string>{"apple", "banana"}, 2);
    check("empty", std::vector<std::string>{}, 0);
    check("single", std::vector<std::string>{"x"}, 1);
    check("empty-strings", std::vector<std::string>{"", ""}, 2);
    check("non-ascii", std::vector<std::string>{"é", "日本語"}, 2);
    check("duplicates", std::vector<std::string>{"a", "a", "a"}, 3);
    check("ten", std::vector<std::string>{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, 10);
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Length.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

final class Length {
  private Length() {}

  /** Returns the number of items in items. */
  static int length(String[] items) {
    // length is a field of every array, so it has no parentheses.
    return items.length;
  }
}
LengthTest.java 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

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 LengthTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("three", new String[] {"a", "b", "c"}, 3),
        Arguments.of("two-words", new String[] {"apple", "banana"}, 2),
        Arguments.of("empty", new String[] {}, 0),
        Arguments.of("single", new String[] {"x"}, 1),
        Arguments.of("empty-strings", new String[] {"", ""}, 2),
        Arguments.of("non-ascii", new String[] {"é", "日本語"}, 2),
        Arguments.of("duplicates", new String[] {"a", "a", "a"}, 3),
        Arguments.of("ten", new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, 10));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void length(String name, String[] items, int want) {
    assertEquals(want, Length.length(items));
  }
}
length.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

#include "length.h"

#include <stddef.h>

size_t length(const char *const *items) {
    size_t n = 0;
    // An empty string is not a null pointer, so it counts as an item.
    while (items[n] != NULL) {
        n++;
    }
    return n;
}
length.h 14 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

#ifndef LENGTH_H
#define LENGTH_H

#include <stddef.h>

// length returns the number of strings in items, which ends with a null
// pointer, like argv. A function gets a pointer, so sizeof cannot give the
// length; the null pointer marks the end instead.
size_t length(const char *const *items);

#endif
test_length.c 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

#include "length.h"

#include <stddef.h>
#include <stdio.h>

static int failures = 0;

static void check(const char *name, const char *const *items, size_t want) {
    if (length(items) != want) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

// Each list ends with NULL. The compound literal keeps each case on one line.
#define CHECK(name, want, ...) check(name, (const char *const[]){__VA_ARGS__}, want)

int main(void) {
    CHECK("three", 3, "a", "b", "c", NULL);
    CHECK("two-words", 2, "apple", "banana", NULL);
    CHECK("empty", 0, NULL);
    CHECK("single", 1, "x", NULL);
    CHECK("empty-strings", 2, "", "", NULL);
    CHECK("non-ascii", 2, "é", "日本語", NULL);
    CHECK("duplicates", 3, "a", "a", "a", NULL);
    CHECK("ten", 10, "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", NULL);
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Length.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

public static class Length
{
    // Length is a property of every array. A List<T> has Count instead.
    public static int Of(string[] items) => items.Length;
}
LengthTests.cs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

using Xunit;

public sealed class LengthTests
{
    public static TheoryData<string, string[], int> Cases => new()
    {
        { "three", new string[] { "a", "b", "c" }, 3 },
        { "two-words", new string[] { "apple", "banana" }, 2 },
        { "empty", new string[0], 0 },
        { "single", new string[] { "x" }, 1 },
        { "empty-strings", new string[] { "", "" }, 2 },
        { "non-ascii", new string[] { "é", "日本語" }, 2 },
        { "duplicates", new string[] { "a", "a", "a" }, 3 },
        { "ten", new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }, 10 },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Check(string name, string[] items, int want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Length.Of(items));
    }
}
length.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

/**
 * @param {string[]} items
 * @returns {number}
 */
export function length(items) {
  // length is one more than the highest index. With no holes, that is the
  // number of items.
  return items.length;
}
length.test.js 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

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

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

const cases = [
  ["three", ["a", "b", "c"], 3],
  ["two-words", ["apple", "banana"], 2],
  ["empty", [], 0],
  ["single", ["x"], 1],
  ["empty-strings", ["", ""], 2],
  ["non-ascii", ["é", "日本語"], 2],
  ["duplicates", ["a", "a", "a"], 3],
  ["ten", ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 10],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.equal(length(items), want);
  });
}
length.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

export function length(items: readonly string[]): number {
  // length is one more than the highest index. With no holes, that is the
  // number of items.
  return items.length;
}
length.test.ts 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

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

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

const cases: [string, string[], number][] = [
  ["three", ["a", "b", "c"], 3],
  ["two-words", ["apple", "banana"], 2],
  ["empty", [], 0],
  ["single", ["x"], 1],
  ["empty-strings", ["", ""], 2],
  ["non-ascii", ["é", "日本語"], 2],
  ["duplicates", ["a", "a", "a"], 3],
  ["ten", ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 10],
];

for (const [name, items, want] of cases) {
  test(name, () => {
    assert.equal(length(items), want);
  });
}
length.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

// Package arraylength counts the items of a slice.
package arraylength

// Length returns the number of items in items. It is 0 for a nil slice.
func Length(items []string) int {
	return len(items)
}
length_test.go 32 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

package arraylength

import "testing"

var cases = []struct {
	name  string
	items []string
	want  int
}{
	{"three", []string{"a", "b", "c"}, 3},
	{"two-words", []string{"apple", "banana"}, 2},
	{"empty", []string{}, 0},
	{"single", []string{"x"}, 1},
	{"empty-strings", []string{"", ""}, 2},
	{"non-ascii", []string{"é", "日本語"}, 2},
	{"duplicates", []string{"a", "a", "a"}, 3},
	{"ten", []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"}, 10},
}

func TestLength(t *testing.T) {
	for _, c := range cases {
		if got := Length(c.items); got != c.want {
			t.Errorf("%s: got %d, want %d", c.name, got, c.want)
		}
	}
	if got := Length(nil); got != 0 {
		t.Errorf("nil: got %d, want 0", got)
	}
}
length.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

/// Returns the number of items in items.
pub fn length(items: &[&str]) -> usize {
    // len counts the items. str::len would count the bytes of one string.
    items.len()
}
tests/length_test.rs 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/get-the-length-of-an-array/.

use algo_get_the_length_of_an_array::length;

#[test]
fn cases() {
    let cases: &[(&str, &[&str], usize)] = &[
        ("three", &["a", "b", "c"], 3),
        ("two-words", &["apple", "banana"], 2),
        ("empty", &[], 0),
        ("single", &["x"], 1),
        ("empty-strings", &["", ""], 2),
        ("non-ascii", &["é", "日本語"], 2),
        ("duplicates", &["a", "a", "a"], 3),
        ("ten", &["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], 10),
    ];
    for &(name, items, want) in cases {
        assert_eq!(length(items), want, "{name}");
    }
}
length.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-length-of-an-array/.

# length ITEM...
# Prints the number of arguments. To count an array, call it as
# length "${a[@]}", or use ${#a[@]} directly.
length() {
  printf '%s\n' "$#"
}
test_length.bats 25 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/get-the-length-of-an-array/.

bats_require_minimum_version 1.5.0

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

check() { # check WANT ITEM...
  local want=$1 got
  shift
  got=$(length "$@")
  [ "$got" = "$want" ] || { printf 'got:  %s\nwant: %s\n' "$got" "$want"; return 1; }
}

@test "three" { check 3 "a" "b" "c"; }
@test "two-words" { check 2 "apple" "banana"; }
@test "empty" { check 0; }
@test "single" { check 1 "x"; }
@test "empty-strings" { check 2 "" ""; }
@test "non-ascii" { check 2 "é" "日本語"; }
@test "duplicates" { check 3 "a" "a" "a"; }
@test "ten" { check 10 "0" "1" "2" "3" "4" "5" "6" "7" "8" "9"; }

References

  1. The Python Standard Library, Built-in Functions, len()
  2. MDN Web Docs, Array length, Description
  3. The Java Language Specification, Java SE 25 Edition, 10.7 Array Members
  4. .NET API reference, Array.Length property, Property Value
  5. The Go Programming Language Specification, Length and capacity
  6. cppreference.com, C main function, Parameters
  7. cppreference.com, std::size, std::ssize, Return value
  8. Bash Reference Manual, 6.7 Arrays
  9. The Java Tutorials, Restrictions on Generics, Cannot Instantiate Generic Types with Primitive Types
  10. The Go Programming Language Specification, Slice expressions
  11. Rust standard library, struct Vec, with_capacity
  12. cppreference.com, C sizeof operator, Notes
  13. cppreference.com, Arithmetic operators, Overflows

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