Logo

Programming-Idioms

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

Idiom #44 Insert element in list

Insert the element x at position i in the list s. Further elements must be shifted to the right.

Inserting the element x at a given position in the list s
s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x

Extend slice by 1 (it may trigger a copy of the underlying array).
Then shift elements to the right.
Then set s[i].
import "slices"
s = slices.Insert(s, i, x)

This generic func slices.Insert works for all slice types
s.insert (s.begin () + i, x);

New implementation...