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

Idiom #19 Reverse a list

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

x = x.reverse();
with Ada.Containers.Vectors;
use Ada.Containers;
X.Reverse_Elements;
(reverse x)
#include <algorithm>
std::reverse(begin(x), end(x));
System.Collections.Generic;
x.Reverse();
import std.range;
auto y = x.retro;
import std.algorithm;
reverse(x);
x.reversed.toList()
Enum.reverse(x)
lists:reverse(List)
for i, j := 0, len(x)-1; i < j; i, j = i+1, j-1 {
	x[i], x[j] = x[j], x[i]
}
reverse x
import java.util.List;
static <T> void reverse(List<T> x){
	int n = x.size();
	for(int i=0;i<n/2;i++){
		T tmp = x.get(i);
		x.set(i, x.get(n-i-1));
		x.set(n-i-1, tmp);
	}
}
import java.util.Collections;
Collections.reverse(x);
rev = {}
for i=#x, 1, -1 do
	rev[#rev+1] = x[i]
end
$x = array_reverse($x, true);
var n,i: integer;
	tmp:TElement;
[...]
n:= length(x);
for i := 0 to (n div 2)-1 do
	begin
		tmp := x[i];
		x[i] := x[n-i-1];
		x[n-i-1] := tmp;
	end;
var n,i: integer;
[...]
n:= length(x);
setlength(x, n+1);
for i := 0 to (n div 2)-1 do
	begin
		x[n] := x[i];
		x[i] := x[n-i-1];
		x[n-i-1] := x[n];
	end;
setlength(x, n);
my @list = ('words', 'of', 'list', 'a', 'reverse');
my @reversed = reverse @list;
x = reversed(x)
x = x[::-1]
x.reverse!
let y: Vec<_> = x.iter().rev().collect();
val items = List(1, 2, 3, 4, 5)
items.reverse

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms