# 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 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? Nov 10, 2021 at 17:36
• Yes, that's fine 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***). 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). Nov 12, 2021 at 0:41

# ><>, 4 3 bytes

i#o


Try it online!

Lol, ><> ties with beats Jelly & 05AB1E. Terminates with an error.

-1 thanks to @Manny Queen.

# How does it work?

     The instruction pointer (IP) is currently moving right
i    Take input as a character
#   Reflect - The IP starts moving left
i    Take input again
o  Output that
#   Reflect - The IP starts moving right again
o  Output the first input we took - the inputs are now swapped

And now, we're moving left and back at the start again on i + moving right.
This loops forever (i.e. until erroring when we're out of input)
because there is no halt instruction (;)
This is essentially executing "iioo" in an infinite loop.

• no longer beats Vyxal Nov 11, 2021 at 8:36
• @wasif Oh well, still beats Jelly and osabie. Nov 11, 2021 at 9:14

# Python 3, 34 bytes

f=lambda l:l and l[1::-1]+f(l[2:])


Try it online!

When l is empty (which makes it falsy), return it directly. Otherwise, reverse the first two elements and make a recursive call for the rest.

# Vyxalr, 2 bytes

yY


Try it Online!

Explanation:

y  # Uninterleave
Y # Interleave

• What does the r flag do? Nov 10, 2021 at 17:49
• @ZippyMagician The r flag makes all commands take their arguments in reverse order. That doesn't affect y since it only has one argument, but it does affect Y, meaning that the program is essentially equivalent to y$Y, which swaps the halves before interleaving. Nov 10, 2021 at 17:53 # Haskell, 22 bytes f(a:b:c)=b:a:f c f x=x  Try it online! • f=concatMap(reverse.take 2).iterate(drop 2) Nov 22, 2021 at 21:13 • @Roman Czyborra nice but there's nothing stopping iterate.. that way works fine Nov 23, 2021 at 0:06 # convey, 7 bytes I knew I should have implemented SpaceChem's flipflop operator, then this would be 5 bytes. :-) -6 byte by @Manny Queen }?{ }~1  Try it online! { puts the input list on the conveyor, } prints the result. On the ? the elements try to go down if they can. On the ~ they will wait for 1 tick before going to the output, thus starting with the first item, every second element is delayed for two ticks. ### 13 bytes },< {@^ 0" 1^  Try it online! The lower loop 0"\1^ copies 0 1 0 1 … into choose @. The input is thus split into two paths. The right one takes a little bit longer, so the other number can overtake it before joining , again. • The second one can be made shorter with some rearrangement. – m90 Nov 11, 2021 at 6:56 • This makes me want to learn convey. It looks awesome. Nov 11, 2021 at 18:33 • @MannyQueen, m90 thanks! Multiple outputs are well defined when they don't fire at the same step, so this is a very neat solution! – xash Nov 12, 2021 at 18:21 # brainfuck, 9 bytes ,[>,.<.,]  Try it online! # Rust v1.37.0, 5955 47 bytes |a:&[_]|(0..).zip(a).map(|i|a[i.0^1]).collect()  Try it online! -2 bytes thanks to ZippyMagician -2 bytes thanks to alephalpha -8 bytes thanks to (0..).zip(a) Rust is not a golfy language... Port of the C# and JS answers v1.37.0 is the version available on TIO # Rust stable, 54 bytes |a:&[_]|a.chunks(2).flat_map(|a|[a[1],a[0]]).collect()  Try it online! Thanks to ZippyMagician for this slightly golfier answer on the latest version of Rust. • If you don’t use tio's outdated version of rust, |a:&[i32]|a.chunks(2).flat_map(|a|[a[1],a[0]]).collect() is 3 bytes shorter Nov 11, 2021 at 1:22 • If you do, 57 bytes Nov 11, 2021 at 1:24 • I think you can use &[_] instead of &[i32]. Nov 11, 2021 at 1:36 • @ZippyMagician I managed to outgolf your stable rust answer with TIO's outdated version of rust :P Nov 18, 2021 at 17:44 # Python 2, 30 bytes def f(a,b,*m):print b,a,;f(*m)  Try it online! The function f takes input splatted like f(1,2,3,4,5,6), and prints the output space-separated, terminating with error. 34 bytes lambda l:map(l.pop,len(l)/2*[1,0])  Try it online! This works by alternating popping the elements at index 1 and index 0. # Wolfram Language (Mathematica), 22 bytes 0<##<1||#2&&#&&#0@##3&  Try it online! Input [L...], and returns in an And. Works on integer inputs. ### Wolfram Language (Mathematica), 24 bytes {}=={##}||#2&&#&&#0@##3&  Try it online! Input [L...], and returns in an And. Works on non-boolean inputs. ### Wolfram Language (Mathematica), 26 bytes #2~##&~#&@@@#~Partition~2&  Try it online! Input [L], and returns a list. Works. • #~Partition~2~Reverse~2& is –2 bytes, if the OP doesn't mind the extra braces in the output: {1, 2, 3, 4, 5, 6}{{2, 1}, {4, 3}, {6, 5}} Nov 11, 2021 at 5:39 • @theorist IMO, that doesn't output what the specs ask for - it outputs a list of pairs. – att Nov 11, 2021 at 6:50 • Yeah, figured you'd say that :). Could you save anything using BlockMap instead of Partition? E.g., BlockMap[Reverse,#,2]& is 2 bytes shorter than #~Partition~2~Reverse~2&. And how would you implement your function in the MMA front end? E.g., list={1,2,3,4,5,6} #2~##&~#&@@@#~Partition~2&@list doesn't work. Nov 11, 2021 at 7:30 • @theorist I initially thought about BlockMap, but arguments to the function are provided as a list, so ...@@# is required, making Partition with @@@ shorter. Use ##&[#2,#]& instead; I'm not sure why infix ##& is recognized in wolframscript but not in a notebook. – att Nov 11, 2021 at 7:36 # JavaScript (ES6), 23 bytes x=>x.map((_,i)=>x[i^1])  The [i^1] is thanks to m90 in TNB Try it online! # Python 3, 36 bytes lambda a:sum(zip(a[1::2],a[::2]),())  Try it online! # Python 3 + numpy, 31 bytes lambda m:m[~-(m==m).cumsum()^1]  Try it online! Expects a numpy array. Most of the code is about avoiding referencing numpy directly, so we can avoid the explicit import. It then calculates the indices directly by xoring a counter with 1. • (m*0).argsort() should work for -2. – ovs Nov 13, 2021 at 16:02 • @ovs, only up to len(m)==16. From 17 numpy uses an unstable sort algorithm by default. tio.run/##DcoxDoAgDADAnVd0bB1MjIvxNwyADLRNwQE/… Nov 13, 2021 at 16:11 # C (clang), 53 $$\\cdots$/extract_tex] 43 42 bytes f(*l,n){*l^=l[1]^(l[1]=*l);n&&f(l+2,n-2);}  Try it online! Inputs a pointer in an int array and the array's length (since pointers in C carry no length info). Swaps every two elements in place. • this also modifies past the end of the array – att Nov 10, 2021 at 18:51 • @att I know, what's the problem? Nov 10, 2021 at 18:57 # Ruby, 26 bytes ->l{r=-1;l.map{l[1^r+=1]}}  Try it online! # Ly, 7 bytes ir[foo]  Try it online! Pretty straightforward, but might be worth posting since it's almost pronounceable. :) ir -- read input codepoints into the stack, reverse the order [ ] -- while the stack isn't empty foo -- flip the top two entries and print as characters  # Cubix, 14 bytes ..@.i?i.o;o;.^  Try it online! This is the first time I've tried to use Cubix, so I wouldn't be suprised if it's possible to do this with less code. It's a hard language to explain, since it's a 2D language where the code is wrapped around a cube. So the directions the instruction pointer take a hard to show in a description. I'll include a link to the online interpreter since it has a debug mode when you can see the way the code iterates through the cells. But I'll try to explain it too... ..@.i?i.o;o;.^ - code before it's wrapped on the cube... i - (1) starts here, input a codepoint ? - branch if top of stack, <0 "left", >0 "right" @ - "left" (true on EOF), halt program ^ - "right", set IP direction to "up" ? - same branch, but coming from another direction i - "right", input another codepoint o; - output top of stack as char, pop it off stack o; - repeat... code wraps back to (1)  The . characters are no-ops and are needed to place the other characters in the right position so they will wrap into place on the cube. Here's a link to the online interpreter http://ethproductions.github.io/cubix/?code=Li5ALmk/aS5vO287Ll4=&input=MTIzNDU2Nzg=&speed=20 # J, 9 bytes [:,_2|.$  Try it online! # 4, 22 bytes 3.72082072152152072094  Try it online! Readable + explanation: 3. 720 820 721 521 520 720 9 4 ^^------------------------------ mandatory prefix ^^^-------------------------- initial input in cell 20 ^^^-----------------^---- loop while cell 20 is nonzero ^^^------------------ input to cell 21 ^^^-------------- output cell 21 ^^^---------- output cell 20 ^^^------ input to cell 20 ^---- end loop ^-- exit  Corresponding Quartic program: decl a, b input a loop a input b print b print a input a end  # AWK, 43 41 bytes {for(;++n<NF;n++)$n+=$(n+1)-($(n+1)=$n)}1  Thanks for Dominic van Essen for 2 less bytes! Try it online! { for(;++n<NF;n++) Starts a loop though the numbers. n has to start as 1, because$0 is the whole line.
$n+=$(n+1)-($(n+1)=$n)  Swap the numbers two by two.
Readable: a += b - (b = a)
}
1                       Prints the line.

• If you swap ++n for n=1 (same bytes), it'll also work for subsequent lines of input... (currently the second 'try it online' line fails) Nov 13, 2021 at 18:22
• You are right!! Thanks for that. Nov 13, 2021 at 18:33
• ...or 41 bytes if you don't care about subsequent lines (and I don't think you need to care about them here...) Nov 13, 2021 at 18:39

# T-SQL, 32 bytes

Input is a table variable

SELECT a FROM @ ORDER BY b+b%2*2


Try it online

# CLC-INTERCAL, 95 67 bytes.

Why does CLC-INTERCAL 1.-94.-2 lack !1~.1'? I could have golfed off one byte.

DOCOMEFROM#9(1)DOWRITEIN.1+.2DDOCOMEFROM'.1~.1'~#1(9)DOREADOUT.2+.1


Copy and paste to try it online!

## Usage

• Each item of list must be in ONE to SIX FIVE FIVE THREE FIVE (inclusive); ZERO for end of list.
• Given from STDIN, delimited with a LF.
• Outputs to STDOUT, as roman number.

## Try these inputs

ONE
TWO
ONE
TWO
ZERO

ONE
TWO
THREE
FOUR
FIVE
SIX
ZERO


# Desmos, 39 38 bytes

l=[1...L.length]
f(L)=L[l-1+2mod(l,2)]


Try It On Desmos!

Try It On Desmos! - Prettified

# BQN, 10 9 bytesSBCS

-1 byte thanks to Razetime!

⥊·⌽˘∘‿2⊸⥊


Run online!

∘‿2⥊𝕩 Reshape the input into a matrix with 2 columns and and the necessary number of rows.
⌽˘ Reverse horizontally (Swap the 2 columns).
⥊ Flatten into a vector.

An alternative using the Under operator at 10 bytes:

⌽˘⌾(∘‿2⊸⥊)


Try it online!

• useful userscript: github.com/razetime/userscripts/blob/main/bqncgcc.user.js Dec 10, 2021 at 10:10
• @Rezetime thanks and thanks! I already read that Nothing is supposed to be useful in trains, now I see why
– ovs
Dec 10, 2021 at 10:28
• TIL about using ∘ with Reshape, fascinating. Jul 14, 2022 at 17:30

# Jelly, 4 bytes

s2UF


Try It Online!

s2    Slices of length 2
U   Reverse each
F  Flatten


# Perl 5 -p, 21 bytes

s/(\S+) (\S+)/$2$1/g


Try it online!

# APL+WIN, 17 bytes

Prompts for vector

,⌽((.5×⍴r),2)⍴r←⎕


Try it online! Thanks to Dyalog Classic

# Zsh, 18 bytes

for a b;<<<$b<<<$a

Attempt This Online!

# C# (.NET Core) with Linq, 32 26 bytes

a=>a.Select((n,i)=>a[i^1])


Try it online!

-8 bytes thanks to m90's witchcraft

# C# (.NET Core), 73 bytes

a=>{for(int i=0,d=0;i<a.Length;i++){d=a[i];a[i]=a[++i];a[i]=d;}return a;}


Try it online!

a:?
b:0
n:0
m:3
b
Ea,Ib=n,,b:1,,x:i,+1,Ib=m,,b:0,,Oi,,Ox


Try it online!

Input is the first argument.

# Rockstar, 98 bytes

Listen to B
cut B with ","
I is 0
while I is less than B
shout B at I+1
shout B at I
Build I up up


Try it online!
(Must manually copy-paste code)

Takes input as comma-separated string of numbers eg:

1,2,3,4,5,6


Outputs as newline-separated string of numbers eg:

2
1
4
3
6
5


Rockstar has no modulo, and no bitwise operators, so porting the other solutions is out of the question.

### Explanation

Listen to B             ; Read input to B
cut B with ","          ; Split B on ","
I is 0                  ; Set I to 0
while I is less than B  ; While I < B.length
; (Rockstar Arrays automatically coerce to length when used as a scalar)
shout B at I+1          ; Print B[I+1] with trailing newline
shout B at I            ; Print B[I] with trailing newline
Build I up up           ; Increment I twice (each 'up' increments)


# Python 3.8 (pre-release), 35 bytes

def f(m):*m[1:],_,m[::2]=*m,m[1::2]


Try it online!

In-place. Essentially a golfed version of m[1::2],m[::2]=m[::2],m[1::2]`

• Is there something special about the 3.8 prerelease? Nov 11, 2021 at 1:17
• @ChrisBouchard it just happens to be the latest version available on tio. The walrss operator can be useful for glfing. Nov 11, 2021 at 4:17
• I guess TIO just hasn't updated their python in a while? 3.8 was fully released Oct 2019, 3.9 is the most recent full release, and 3.10 is the current pre-release. Nov 11, 2021 at 20:06