Logo

Programming-Idioms

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

Idiom #19 Reverse a list

Reverse the order of the elements of the list x.
This may reverse "in-place" and destroy the original ordering.

for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
	x[i], x[j] = x[j], x[i]
}

This loop reverts "in-place" (in the original list, not creating a new one).
func reverse[T any](x []T) {
	for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
		x[i], x[j] = x[j], x[i]
	}
}

This generic function works for any type parameter T.

It operates in-place.
import "slices"
slices.Reverse(x)
with Ada.Containers.Vectors;
use Ada.Containers;
X.Reverse_Elements;

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