Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #29 Remove item from list, by its index

Remove i-th item from list items.
This will alter the original list or return a new list, depending on which is more idiomatic.
Note that in most languages, the smallest valid value for i is 0.

copy(items[i:], items[i+1:])
items[len(items)-1] = nil
items = items[:len(items)-1]

This code is for pointer value type, and has no memory leak.
import "slices"
items = slices.Delete(items, i, i+1)

This generic func slices.Delete works for all slice types.
items = append(items[:i], items[i+1:]...)

If items elements are pointers or structs with pointers, then refer to the SliceTricks page to avoid memory leaks.
with Ada.Containers.Vectors;
use Ada.Containers;
Items.Delete (I);

New implementation...
< >
programming-idioms.org