Taskintro
Loop with an index
Also called loop with index and value, enumerate a list, find all positions, indexes of a value, for loop with index, entries, enumerate, iterate with index.
Loop over a list with the index and the item together, collect the index of each match, and avoid the loops that give only the first match or the wrong index.
- Evidence
- Code in 10 languages
Task
Find each place where a value occurs in a list. The function positions(items, target) returns the 0-based index of each item that equals target, in increasing order. For example, positions(["a", "b", "a", "c"], "a") is [0, 2]. If no item matches, the result is empty.
items is a list of 0 to 1000 strings, and target is a string. Two strings are equal when they have the same characters, so the test is case-sensitive. The loop needs the index and the item in each pass.
Solutions
| Language | The index and the item |
|---|---|
| Python | for i, x in enumerate(items): |
| JavaScript, TypeScript | for (const [i, x] of items.entries()) |
| Go | for i, x := range items |
| Rust | for (i, x) in items.iter().enumerate() |
| Java, C#, C, C++ | for (i = 0; i < n; i++) and items[i] |
| Bash | for i in "${!a[@]}" and ${a[i]} |
- Python. "the position index and corresponding value can be retrieved at the same time using the enumerate() function"1.
- JavaScript and TypeScript.
entries()"returns a new array iterator object that contains the key/value pairs for each index in the array"2. The loop takes each pair apart with[i, x]. - Go. For a slice,
rangegives the index first and the item second3. - Rust.
enumerate"yields pairs (i, val) , where i is the current index of iteration and val is the value returned by the iterator"4. The index is ausize. - Java, C#, C and C++. A counted loop gives the index, and
items[i]gives the item. Java compares withequals, and C withstrcmp, which "Compares two null-terminated byte strings lexicographically"5 and returns 0 when they are equal. - Bash.
${!name[@]}"expands to the list of array indices (keys) assigned in name"6. The function takes the target and then the items as arguments, and prints one index on each line.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no items, so the loop body does not run.none: no item matches, so the result is empty.all: each item matches, so the result is each index.last: the match is the last item. A loop that stops atn - 1misses it. See off-by-one errors.case:"A"does not equal"a".empty-string: the target is the empty string, and it matches only the empty items.
Pitfalls
- A search method finds only the first match. Python
list.indexreturns the "zero-based index of the first occurrence of value in the list" and "Raises a ValueError if there is no such item"1. Use a loop to find each match:
items = ["a", "b", "a", "c"]
print(items.index("a"))
print([i for i, x in enumerate(items) if x == "a"])
try:
items.index("z")
except ValueError:
print("ValueError")
0
[0, 2]
ValueError
- Java
==compares references, not the characters. For two objects, "the result of == is true if the operand values are both null or both refer to the same object or array; otherwise, the result is false"7. A string made at run time is a different object, so==misses it:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
String[] items = {"a", new String("a")};
String target = "a";
List<Integer> same = new ArrayList<>();
List<Integer> equal = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
if (items[i] == target) {
same.add(i);
}
if (items[i].equals(target)) {
equal.add(i);
}
}
System.out.println("== " + same + " equals " + equal);
}
}
== [0] equals [0, 1]
- Rust
enumeratecounts the items that it sees. The index is "the current index of iteration"4, not the position in the list. Ifenumeratecomes afterskiporfilter, the count starts again at 0. Putenumeratefirst:
fn main() {
let items = ["x", "a", "b"];
let late: Vec<(usize, &str)> = items.iter().copied().skip(1).enumerate().collect();
let early: Vec<(usize, &str)> = items.iter().copied().enumerate().skip(1).collect();
println!("{late:?}");
println!("{early:?}");
}
[(0, "a"), (1, "b")]
[(1, "a"), (2, "b")]
- The index of a Go string loop is a byte index. For a string,
rangegives "the index of the first byte of successive UTF-8-encoded code points"3. After a character outside ASCII, the index skips numbers. Loop over a slice of strings, as here, or convert the string to[]runefirst.
See for-each loop for the loop without an index.
Related tasks
- Loop over a collection: visit each item without the index.
- Write a counted loop: a loop over the numbers alone.
- Loop over nested loops: two indexes, one for the row and one for the column.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-an-index/.
def positions(items: list[str], target: str) -> list[int]:
"""Return the index of each item that equals target."""
out = []
# enumerate gives the index and the item together.
for i, x in enumerate(items):
if x == target:
out.append(i)
return out
test_positions.py 23 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-an-index/.
import pytest
from positions import positions
CASES = {
"two-matches": ((["a", "b", "a", "c"], "a"), [0, 2]),
"words": ((["red", "green", "blue", "green"], "green"), [1, 3]),
"empty": (([], "a"), []),
"none": ((["a", "b"], "z"), []),
"all": ((["x", "x", "x"], "x"), [0, 1, 2]),
"last": ((["a", "b", "c"], "c"), [2]),
"case": ((["A", "a"], "a"), [1]),
"empty-string": ((["", "a", ""], ""), [0, 2]),
}
@pytest.mark.parametrize("name", CASES)
def test_positions(name):
args, want = CASES[name]
assert positions(*args) == want
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
#include "positions.hpp"
#include <cstddef>
#include <string>
#include <vector>
std::vector<std::size_t> positions(const std::vector<std::string> &items, const std::string &target) {
std::vector<std::size_t> out;
for (std::size_t i = 0; i < items.size(); i++) {
if (items[i] == target) {
out.push_back(i);
}
}
return out;
}
positions.hpp 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
#pragma once
#include <cstddef>
#include <string>
#include <vector>
// positions returns the index of each item that equals target.
std::vector<std::size_t> positions(const std::vector<std::string> &items, const std::string &target);
test_positions.cpp 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
#include "positions.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, const std::string &target,
const std::vector<std::size_t> &want) {
if (positions(items, target) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("two-matches", {"a", "b", "a", "c"}, "a", {0, 2});
check("words", {"red", "green", "blue", "green"}, "green", {1, 3});
check("empty", {}, "a", {});
check("none", {"a", "b"}, "z", {});
check("all", {"x", "x", "x"}, "x", {0, 1, 2});
check("last", {"a", "b", "c"}, "c", {2});
check("case", {"A", "a"}, "a", {1});
check("empty-string", {"", "a", ""}, "", {0, 2});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
import java.util.ArrayList;
import java.util.List;
final class Positions {
private Positions() {}
/** Returns the index of each item that equals target. */
static List<Integer> positions(String[] items, String target) {
List<Integer> out = new ArrayList<>();
for (int i = 0; i < items.length; i++) {
// equals compares the characters. == would compare the references.
if (items[i].equals(target)) {
out.add(i);
}
}
return out;
}
}
PositionsTest.java 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
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 PositionsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("two-matches", new String[] {"a", "b", "a", "c"}, "a", List.of(0, 2)),
Arguments.of("words", new String[] {"red", "green", "blue", "green"}, "green", List.of(1, 3)),
Arguments.of("empty", new String[] {}, "a", List.of()),
Arguments.of("none", new String[] {"a", "b"}, "z", List.of()),
Arguments.of("all", new String[] {"x", "x", "x"}, "x", List.of(0, 1, 2)),
Arguments.of("last", new String[] {"a", "b", "c"}, "c", List.of(2)),
Arguments.of("case", new String[] {"A", "a"}, "a", List.of(1)),
Arguments.of("empty-string", new String[] {"", "a", ""}, "", List.of(0, 2)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void positions(String name, String[] items, String target, List<Integer> want) {
assertEquals(want, Positions.positions(items, target), name);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
#include "positions.h"
#include <string.h>
size_t positions(const char *const *items, size_t n, const char *target, size_t *out) {
size_t k = 0;
for (size_t i = 0; i < n; i++) {
// strcmp returns 0 when the strings are equal. == would compare the pointers.
if (strcmp(items[i], target) == 0) {
out[k++] = i;
}
}
return k;
}
positions.h 13 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
#ifndef POSITIONS_H
#define POSITIONS_H
#include <stddef.h>
// positions writes the index of each of the n items that equals target to out,
// which must have room for n values, and returns the number of indexes.
size_t positions(const char *const *items, size_t n, const char *target, size_t *out);
#endif
test_positions.c 50 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
#include "positions.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, const char *const *items, size_t n, const char *target,
const size_t *want, size_t wn) {
size_t out[8];
size_t k = positions(items, n, target, out);
if (k != wn || (k > 0 && memcmp(out, want, k * sizeof *out) != 0)) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
#define LEN(a) (sizeof(a) / sizeof((a)[0]))
int main(void) {
const char *two[] = {"a", "b", "a", "c"};
const size_t two_w[] = {0, 2};
check("two-matches", two, LEN(two), "a", two_w, LEN(two_w));
const char *words[] = {"red", "green", "blue", "green"};
const size_t words_w[] = {1, 3};
check("words", words, LEN(words), "green", words_w, LEN(words_w));
check("empty", NULL, 0, "a", NULL, 0);
const char *none[] = {"a", "b"};
check("none", none, LEN(none), "z", NULL, 0);
const char *all[] = {"x", "x", "x"};
const size_t all_w[] = {0, 1, 2};
check("all", all, LEN(all), "x", all_w, LEN(all_w));
const char *last[] = {"a", "b", "c"};
const size_t last_w[] = {2};
check("last", last, LEN(last), "c", last_w, LEN(last_w));
const char *cs[] = {"A", "a"};
const size_t cs_w[] = {1};
check("case", cs, LEN(cs), "a", cs_w, LEN(cs_w));
const char *es[] = {"", "a", ""};
const size_t es_w[] = {0, 2};
check("empty-string", es, LEN(es), "", es_w, LEN(es_w));
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
public static class Positions
{
// Returns the index of each item that equals target.
public static List<int> Of(IReadOnlyList<string> items, string target)
{
var result = new List<int>();
for (int i = 0; i < items.Count; i++)
{
// string.Equals compares the characters, with the ordinal rules.
if (string.Equals(items[i], target, StringComparison.Ordinal))
{
result.Add(i);
}
}
return result;
}
}
PositionsTests.cs 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
using Xunit;
public sealed class PositionsTests
{
public static TheoryData<string, string[], string, int[]> Cases => new()
{
{ "two-matches", new[] { "a", "b", "a", "c" }, "a", new[] { 0, 2 } },
{ "words", new[] { "red", "green", "blue", "green" }, "green", new[] { 1, 3 } },
{ "empty", new string[0], "a", new int[0] },
{ "none", new[] { "a", "b" }, "z", new int[0] },
{ "all", new[] { "x", "x", "x" }, "x", new[] { 0, 1, 2 } },
{ "last", new[] { "a", "b", "c" }, "c", new[] { 2 } },
{ "case", new[] { "A", "a" }, "a", new[] { 1 } },
{ "empty-string", new[] { "", "a", "" }, "", new[] { 0, 2 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Check(string name, string[] items, string target, int[] want)
{
Assert.NotNull(name);
Assert.Equal(want, Positions.Of(items, target));
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
/**
* Returns the index of each item that equals target.
* @param {string[]} items
* @param {string} target
* @returns {number[]}
*/
export function positions(items, target) {
const out = [];
// entries() gives [index, item] pairs.
for (const [i, x] of items.entries()) {
if (x === target) {
out.push(i);
}
}
return out;
}
positions.test.js 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { positions } from "./positions.js";
const cases = [
["two-matches", ["a", "b", "a", "c"], "a", [0, 2]],
["words", ["red", "green", "blue", "green"], "green", [1, 3]],
["empty", [], "a", []],
["none", ["a", "b"], "z", []],
["all", ["x", "x", "x"], "x", [0, 1, 2]],
["last", ["a", "b", "c"], "c", [2]],
["case", ["A", "a"], "a", [1]],
["empty-string", ["", "a", ""], "", [0, 2]],
];
for (const [name, items, target, want] of cases) {
test(name, () => {
assert.deepEqual(positions(items, target), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
export function positions(items: readonly string[], target: string): number[] {
const out: number[] = [];
// entries() gives [index, item] pairs.
for (const [i, x] of items.entries()) {
if (x === target) {
out.push(i);
}
}
return out;
}
positions.test.ts 24 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { positions } from "./positions.ts";
const cases: [string, string[], string, number[]][] = [
["two-matches", ["a", "b", "a", "c"], "a", [0, 2]],
["words", ["red", "green", "blue", "green"], "green", [1, 3]],
["empty", [], "a", []],
["none", ["a", "b"], "z", []],
["all", ["x", "x", "x"], "x", [0, 1, 2]],
["last", ["a", "b", "c"], "c", [2]],
["case", ["A", "a"], "a", [1]],
["empty-string", ["", "a", ""], "", [0, 2]],
];
for (const [name, items, target, want] of cases) {
test(name, () => {
assert.deepEqual(positions(items, target), want);
});
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
// Package positions finds each index where a value occurs in a slice.
package positions
// Positions returns the index of each item that equals target.
func Positions(items []string, target string) []int {
out := []int{}
// For a slice, range gives the index and then the item.
for i, x := range items {
if x == target {
out = append(out, i)
}
}
return out
}
positions_test.go 33 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
package positions
import (
"slices"
"testing"
)
var cases = []struct {
name string
items []string
target string
want []int
}{
{"two-matches", []string{"a", "b", "a", "c"}, "a", []int{0, 2}},
{"words", []string{"red", "green", "blue", "green"}, "green", []int{1, 3}},
{"empty", []string{}, "a", []int{}},
{"none", []string{"a", "b"}, "z", []int{}},
{"all", []string{"x", "x", "x"}, "x", []int{0, 1, 2}},
{"last", []string{"a", "b", "c"}, "c", []int{2}},
{"case", []string{"A", "a"}, "a", []int{1}},
{"empty-string", []string{"", "a", ""}, "", []int{0, 2}},
}
func TestPositions(t *testing.T) {
for _, c := range cases {
if got := Positions(c.items, c.target); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
/// Returns the index of each item that equals target.
pub fn positions(items: &[&str], target: &str) -> Vec<usize> {
let mut out = Vec::new();
// enumerate gives (index, item) pairs. It must come before any filter.
for (i, x) in items.iter().enumerate() {
if *x == target {
out.push(i);
}
}
out
}
tests/positions_test.rs 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/loop-with-an-index/.
use algo_loop_with_an_index::positions;
#[test]
fn cases() {
let cases: &[(&str, &[&str], &str, &[usize])] = &[
("two-matches", &["a", "b", "a", "c"], "a", &[0, 2]),
("words", &["red", "green", "blue", "green"], "green", &[1, 3]),
("empty", &[], "a", &[]),
("none", &["a", "b"], "z", &[]),
("all", &["x", "x", "x"], "x", &[0, 1, 2]),
("last", &["a", "b", "c"], "c", &[2]),
("case", &["A", "a"], "a", &[1]),
("empty-string", &["", "a", ""], "", &[0, 2]),
];
for &(name, items, target, want) in cases {
assert_eq!(positions(items, target), want, "{name}");
}
}
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-an-index/.
# positions TARGET ITEM...
# Prints the 0-based index of each item that equals TARGET, one on each line.
positions() {
local target=$1 i
shift
local -a items=("$@")
# ${!items[@]} expands to the indexes of the array.
for i in "${!items[@]}"; do
if [[ ${items[i]} == "$target" ]]; then
printf '%s\n' "$i"
fi
done
}
test_positions.bats 30 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/loop-with-an-index/.
bats_require_minimum_version 1.5.0
setup() {
source "$BATS_TEST_DIRNAME/positions.sh"
}
check() { # check TARGET N ITEM_1 ... ITEM_N WANT...
local target=$1 n=$2
shift 2
local -a items=("${@:1:n}")
shift "$n"
local got want
# The x keeps the trailing newlines, which $(...) removes.
got=$(positions "$target" "${items[@]}"; printf x)
want=$(if (($# > 0)); then printf '%s\n' "$@"; fi; printf x)
[ "$got" = "$want" ] || { printf 'got: %q\nwant: %q\n' "$got" "$want"; return 1; }
}
@test "two-matches" { check a 4 a b a c 0 2; }
@test "words" { check green 4 red green blue green 1 3; }
@test "empty" { check a 0; }
@test "none" { check z 2 a b; }
@test "all" { check x 3 x x x 0 1 2; }
@test "last" { check c 3 a b c 2; }
@test "case" { check a 2 A a 1; }
@test "empty-string" { check "" 3 "" a "" 0 2; }
References
- Data Structures, The Python Tutorial, 5.1 More on Lists; 5.6 Looping Techniques
- Array.prototype.entries(), MDN Web Docs, Description
- The Go Programming Language Specification, For statements with range clause
- Iterator in std::iter, The Rust Standard Library, enumerate
- strcmp, cppreference.com, Description
- Bash Reference Manual, 3.5.3 Shell Parameter Expansion
- The Java Language Specification, Java SE 25 Edition, Chapter 15, 15.21.3 Reference Equality Operators == and !=
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 KYHY8T Edit this page History Report an error Markdown