# Swap every two elements in a list

## Challenge

Let's have a list L of n elements. The task is to swap every two elements in this list.

## Constrains

• the list L has at least two elements
• size of the list L is a multiple of two (i.e. number of elements is even)

### Example

• input: [1,2,3,4,5,6]

• output: [2,1,4,3,6,5]

• input: [0,1,0,1]

• output: [1,0,1,0]

## Rules

• this is code-golf challenge, so the shortest code wins
• standard rules apply for your answer with default I/O rules, so you are allowed to use stdin/stdout, functions/method with the proper parameters and return-type, full programs
• default Loopholes are forbidden.
• Welcome to Code Golf and nice first question! For future reference, we recommend using the Sandbox to get feedback on challenge ideas before posting them to main Commented Nov 10, 2021 at 16:42
• What types of elements must the list support? In particular, is it all right if a solution only works on lists of non-negative/unsigned integers? Commented Nov 10, 2021 at 17:36
• Yes, that's fine Commented Nov 10, 2021 at 20:19
• Can we use a char[] array in a language like C? If so, there is a certain built-in that would make the answer very short (s***). Commented Nov 11, 2021 at 0:29
• Sure, go ahead. However, I'd say that if there are two solutions with the same length, then the more general one wins (the one that works for more inputs/datatypes). Commented Nov 12, 2021 at 0:41

# Knight, 35 bytes

;=aP;=bP WaIb;Ob;Oa;=bN=aP Ia=bP=aP


Try it online!

# rSNBATWPL, 37 bytes

a~(a cond (a{1},0 a)+{a sfro 2}){+for


This is very golfed. It is "bad rSNBATWPL" in that it abuses the syntax very heavily. The ungolfed version of this is:

f = a ~ cond{a} {
(a{1}, a{0}) conc f{a sfro 2}
} { cast.array{""} }


This is a simple recursive lambda function, which iterates pair-by-pair. Some golfs I made to this were:

• Removing whitespace and the unnecessary trailing }, of course
• Substituting cast.array{""} for +for, a very strange way of generating an empty array (works by iterating with a function, + in this case, over an empty array generated when for casts its right input, which is Null, to an array)
• Replacing conc, the concat function, with +
• Replacing a{0} with 0 a, which calls a as a curried binary function. Its second argument is Null, and since calling any primitive value as a function with Null as its input returns it unchanged, this saves a byte for little cost
• Running cond as a binary function. Since rSNBATWPL functions/built-ins are curried, this saves a byte over applying the function three times (which is the traditional way of providing three arguments)
• Replacing f= and f{...} with an implicit recursive call. . is a variable which always refers to the current function, so f{...} can be replaced with .{...} to remove the f=, and any time there's a {...} without a function name, an implicit . is added, allowing me to save another byte by putting it after the +

# Thunno, $$\ 6 \log_{256}(96) \approx \$$ 4.94 bytes

ZlrzZS


Attempt This Online!

#### Explanation

ZlrzZS  # Implicit input     [1, 2, 3, 4, 5, 6]
Zl      # Uninterleave       [[1, 3, 5], [2, 4, 6]]
r     # Reverse            [[2, 4, 6], [1, 3, 5]]
zZ   # Zip                [[2, 1], [4, 3], [6, 5]]
S  # Sum (Flatten)      [2, 1, 4, 3, 6, 5]


# TI-Basic, 19 17 bytes

seq(Ans(I-i²^I),I,1,dim(Ans


i represents the imaginary number.

Takes input in Ans. Output is stored in Ans and is displayed.

-2 bytes thanks to MarcMush.

• -2 bytes: (⁻1) => 𝒾² Commented Nov 5, 2023 at 18:02

# UiuaSBCS, 7 bytes

♭≡⇌↯∞_2


Try it!

-1 thanks to Bubbler

♭≡⇌↯∞_2
↯∞_2  # reshape into matrix with two columns
≡⇌      # reverse columns
♭        # deshape

• Replace ≑~ with ≡ to save 1. Commented Nov 5, 2023 at 22:46
• @Bubbler Of course, thanks! Commented Nov 6, 2023 at 6:28

# Labyrinth, 13 bytes

??!
; \
,\!
@


Try it online!

Takes a list of integers separated by any non-numeric non-null single byte, and prints newline-separated integers. It is important that the input does NOT have a trailing separator, since it is used to detect the end of input.

Loop: ??!\!\,;
??    Take two integers A and B [A B]
!\!\  Print B, newline, A, newline
,     Take the next separator, -1 on EOF
;     Continue loop if not EOF; discard the separator

End: @ (Halt)


# Pyth, 7 bytes

.n_McQ2


Try it online!

• cQ2 chunks of evaluated input in length of 2

• _M maps over reversal in the chunk matrix

• .n flattens it

• Natte's suggested a golf, -1 by replacing the .n with s Commented Nov 21, 2021 at 2:32

# Charcoal, 5 bytes

ＷＳ⟦Ｓι


Try it online! Link is to verbose version of code. Takes newline-terminated input. Explanation:

ＷＳ


Repeat while there is still input...

⟦Ｓι


... output the subsequent input before it.

# Pip-rp, 7 bytes

WVRVUWg


Try it online!

### Explanation

The flags are for input & output formatting: -r reads the program arguments from lines of stdin; -p formats the output as a list rather than concatenating it.

      g  List of arguments
UW   Unweave into a pair of lists, each consisting of every other element
RV     Reverse the order of those two lists
WV       Weave them back together


# Core Maude, 115 bytes

mod S is pr LIST{Nat}. op f : Nat ~> Nat . var A B : Nat . eq f(A B X:[Nat])=
B A f(X:[Nat]). eq f(nil)= nil . endm


The result is obtained by reducing the f function with the input list.

### Example Session

Maude> red f(1 2 3 4 5 6) .  --- Expected: 2 1 4 3 6 5
result NeList{Nat}: 2 1 4 3 6 5
Maude> red f(0 1 0 1) .  --- Expected: 1 0 1 0
result NeList{Nat}: 1 0 1 0


### Ungolfed

mod S is
pr LIST{Nat} .

op f : Nat ~> Nat .

var A B : Nat .

eq f(A B X:[Nat]) = B A f(X:[Nat]) .
eq f(nil) = nil .
endm


Just the straightforward recursive solution. Saved a couple bytes by inlining the type in X:[Nat] rather than declaring it with the var keyword. Doing the same with A and B doesn't change the byte count — just the way the math works out.

# Icon, 47 bytes

procedure f(L)
L[i:=1to*L by 2]:=:L[i+1]&\z
end


Try it online!

# K (oK), 10 bytes

Solution:

,/|:'0N 2#


Try it online!

Explanation:

,/|:'0N 2# / the solution
0N 2# / reshape into n x 2 grid
|:'      / reverse (|:) each (')
,/         / flatten


Alternatives:

• ,/+|+0N 2# - also 10 bytes
• You can switch to ngn/k for 9 bytes: ,/|'0N 2# Commented Nov 12, 2021 at 7:41

proc S L {lmap a\ b $L {lappend M$b $a} set M}  Try it online! # MMIX, 40 bytes (10 instrs) Assumes 8-byte size for list elements. void __mmixware swao(uint64_t *l, size_t len) hexdump (jxd -T): 00000000: 42010009 3f010101 27010101 8fff0000 B¢¡µ?¢¢¢'¢¢¢Ɓ”¡¡ 00000010: 8f020008 afff0008 af020000 e7000010 Ɓ£¡®Ḥ”¡®Ḥ£¡¡ḃ¡¡Ñ 00000020: 5b01fffa f8000000 [¢”«ẏ¡¡¡  Disassembled: swae BZ$1,1F          // if nothing, return
SRU  $1,$1,1        // turn length into loop count
0H      SUBU $1,$1,1        // decrement loop count
LDOU $255,$0,0      // load l[0]
LDOU $2,$0,8        // load l[1]
STOU $255,$0,8      // store the other way
STOU $2,$0,0        // store the other way
INCL $0,16 // l += 2 PBNZ$1,0B          // if loop count isn't yet 0, loop back
1H      POP  0,0            // return


# Perl 5 + -p, 8 bytes

This sets $_ (implicitly printed by -p) to the next line of STDIN (<> - which isn't trimmed via chomp) concatenated with the current line ($_).

$_=<>.$_

Try it online!

or (with -nl -M5.10.0):

say<>.$_ Try it online! # Perl 5 + -p -M5.10.0, 8 bytes This outputs (say) the next line of STDIN (<>), after converting to a number ($-=) to avoid the trailing newline, then the current line is output via -p.

say$-=<> Try it online! # Julia ## 25 bytes !x=x[1:end.|>i->i-(-1)^i] Attempt This Online! ## 24 bytes !x=x[(I=1:end).-(-1).^I]  # ECMAScript 2015 with Lodash (Array), 39 bytes l=>_.chunk(l,2).flatMap(s=>[s[1],s[0]])  Solution below works if array doesn't chunk evenly (l.length % 2 == 1) l=>_.chunk(l,2).flatMap(s=>s.length-1?[s[1],s[0]]:s)  # Arturo, 37 30 bytes $=>[map&[a,b]->@[b,a]|flatten]


Try it

## Prolog - 36 bytes

s([],[]).s([A,B|L],[B,A|R]):-s(L,R).


Non code-golf:

;; swap empty list is empty list
swap([],[]).

;; swap of A,B followed by L is B,A followed by R, where swap(L,R).
swap([A,B|L],[B,A|R]):-swap(L,R).


# Python 3.8 (pre-release), 39 bytes

f=lambda x:x and[x.pop(~len(x)%2)]+f(x)


Try it online!

# Whitespace, 131 bytes





Attempt This Online!

Generated from the following asm2ws program:

2 / GETN / 2 / RCL / 2 / DIV
@LOOP
DUP / BZ %END
0 / GETN
1 / GETN
1 / RCL / PUTN
32 / PUTC
0 / RCL / PUTN
32 /PUTC
1 / SUB / B %LOOP
@END


# Vyxal, 16 bitsv2, 2 bytes

2ẇR


Try it Online!

Bitstring:

0100011100000110


another 2 byter

# Python 3, 48 bytes

f=lambda l:l[::-1][:2]+f(l[2:])if len(l)>1else l


Try it online!

Very simple. For some reason l[:2:-1] doesn't work.

• Fail
– l4m2
Commented Mar 18 at 7:07