[Question]
  [
**This question already has answers here**:
 
 
[Swap Two Values in a List](/questions/236301/swap-two-values-in-a-list)
 (49 answers)
 
Closed 1 year ago.
Given an array of positive integers and two distinct valid indices, return the array with the two elements corresponding to the two indices swapped.
You may choose to use 0-indexing or 1-indexing, but the testcases below will be 0-indexed.
```
array        m n output
[1,2,3,4]    0 1 [2,1,3,4]
[5,8,9]      0 2 [9,8,5]
[11,13,15,3] 1 2 [11,15,13,3]
[11,13,15,3] 2 1 [11,15,13,3]
[11,15,15,3] 2 1 [11,15,15,3]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
  
[Answer]
# C~~/C++~~, ~~53~~ ~~50~~ 39 bytes
```
f(a,m,n)int*a;{a[m]^=a[n]^=a[m]^=a[n];}
```
[Try it online](https://tio.run/##dZDLboMwEEXX@CtGSJVwMlWBNFIrmi9xqWTRpPICUwXKU3w7HcbFyaYbj@eeOw@7ePwqimW5RBpLtNLYZqezSasy/zhpZfnc7tm8tJX5hOZcNxE5YacR1li7ULpgpZhEsHZcFSszQVl1BS4xcII4o/AGNTxBbcZzRVYV55LU/V6KIPi@kvMShQ/pD4QIWpmcm2z6uw0pn4XgodrYiCdSRsWtymnElCCkCAeE5xlJ7Zx6RHhBeGWp/zOSMyFfQuzAYPgPjHfguIF1Mf6QFrfXtBIhJk5LOtR51DmUetR71BNK7tHg0SD5NbeGo0fjDc3LLw)
Saved 11 bytes thanks to @Dennis
[Answer]
# [Operation Flashpoint](https://en.wikipedia.org/wiki/Operation_Flashpoint:_Cold_War_Crisis) scripting language, ~~98~~ 95 bytes
```
f={t=_this;a=t select 0;b=+a;m=t select 1;n=t select 2;a set[m,b select n];a set[n,b select m]}
```
Modifies the array directly.
**Explanation:**
```
t=_this;                   // Give a shorter name for the array of arguments.
a=t select 0;              // Let 'a' be a pointer to the array that we modify.
                           // (The language doesn't have a concept of pointers really,
                           // yet its array variables are pointers to the actual array.)
b=+a;                      // Make a copy of the original array and save a pointer to it
                           // in the variable 'b'. This saves a few bytes later.
m=t select 1;              // Read the index arguments from the input array and save them
n=t select 2;              // to their respective variables.
a set[m,b select n];       // Do the swapping by reading the values from the copy and
a set[n,b select m]        // writing them to the original array. The last semicolon can
                           // be omitted because there are no more statements following 
                           // the last statement.
```
**Call with:**
```
array = [1,2,3,4];
str = format["%1", array];
[array, 0, 1] call f;
hint format["%1\n%2", str, array];
```
**Output:**
[![enter image description here](https://i.stack.imgur.com/sHwSA.jpg)](https://i.stack.imgur.com/sHwSA.jpg)
[Answer]
# JavaScript ES6, ~~36~~ 32 bytes
Look, Ma, no temporary variable!
```
(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]
```
* 4 bytes saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil) bringing [this consensus](https://codegolf.meta.stackexchange.com/a/4942/48934) to my attention.
---
## Try it
Enter a comma separated list of elements for `a` and 2 integers for `m` & `n`.
```
f=
(a,m,n)=>[a[m],a[n]]=[a[n],a[m]]
oninput=_=>o.innerText=(f(b=i.value.split`,`,+j.value,+k.value),b);o.innerText=(f(b=(i.value="5,8,9").split`,`,j.value=0,k.value=2),b)
```
```
*{font-family:sans-serif}input{margin:0 5px 0 0;width:100px;}#j,#k{width:50px;}
```
```
<label for=i>a: </label><input id=i><label for=j>m: </label><input id=j type=number><label for=k>n: </label><input id=k type=number><pre id=o>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṛ,ḷyJ}ị
```
[Try it online!](https://tio.run/##y0rNyan8///hzlk6D3dsr/Sqfbi7@3@x0eHl@o@a1rj//x8dbaijYBSroxCtAGQoGAGxMRCbxOpwKYCkjMFSpkAhCyC2VAACsJQRVMoQqMYQqMMQpMQYLGUMNRBNKhYA "Jelly – Try It Online")
### How it works
```
Ṛ,ḷyJ}ị  Main link. Left argument: [i, j]. Right argument: A (array)
Ṛ        Reverse; yield [j, i].
  ḷ      Left; yield [i, j].
 ,       Pair; yield [[j, i], [i, j]].
    J}   Indices right; yield all indices of A.
   y     Transliterate; replace j with i and i with j.
      ị  Index into A.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~7~~ 6 bytes
```
yyP)w(
```
Indices are 1-based.
[**Try it online!**](https://tio.run/##y00syfn/v7IyQLNc4///aENDBUNjBUNTBeNYrmgjIAkA)
### Explanation
Consider inputs `[11 13 15 3]`, `[2 3]`.
```
yy   % Take two inputs implicitly. Duplicate them
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [2 3]
P    % Flip
     % STACK: [11 13 15 3], [2 3], [11 13 15 3], [3 2]
)    % Reference indexing (pick indexed entries)
     % STACK: [11 13 15 3], [2 3], [15 13]
w    % Swap
     % STACK: [11 13 15 3], [15 13], [2 3]
(    % Assignment indexing (write values into indexed entries). Implicitly display
     % STACK: [11 15 13 3]
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~41~~ 32 bytes
-9 bytes thanks to @notjagan
```
def f(a,m,n):a[m],a[n]=a[n],a[m]
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1EnVydP0yoxOjdWJzE6L9YWROiAuP8TbaMNDXUMjXUMTXWMY7lAag11jDS5Cooy80o0EjX/AwA "Python 3 – Try It Online")
Modifies its argument, which is a [valid output format](https://codegolf.meta.stackexchange.com/a/4942/64121).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 4 bytes
```
{e\}
```
[Try it online!](https://tio.run/##S85KzP2fU133vzo1pvZ/XUGOn25txv9oQwUjBWMFk1gFEDBQMOSKNlWwULCE8EEiRlzRhoYKhsYKhqYKxkBhQwwRIwVDAA "CJam – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 17 16 bytes
```
hV(A=UgV UgW¹hWA
```
[Try it online!](https://tio.run/##y0osKPn/PyNMw9E2ND1MITQ9/NDOjHDH//@jDXWMdIx1TGIVDBQMAQ "Japt – Try It Online")
Saved a byte thanks to ETHproductions
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 48 43 31 bytes
```
(a,m,n)=>a[m]+=a[n]-(a[n]=a[m])
```
[Try it online!](https://tio.run/##bU/LCsIwELz3KxZPCcZCEU81gngTBcGDh9JDiFEW7EaSqIj022tSwQc4sMOys7MP7UfaOtNBhD4p72Hj7NGpJkuVR88JPqiAGq4W97BWSIy/pU9Twvbug2nyuQ5oaYoUqlpETjGDg8w6pkQjiMuZqpp6KFVF9YgllqnAuzL7mXdVDpDOlwASyNyqGh5QFAKKcYyJgDG05Y/hwPr2qEaRl/@OW1jy9mTyncNgVkiG@eCQjvnSxs8GYiBeK/mXve2ztnsC "C# (.NET Core) – Try It Online")
Swaps the numbers in the original array, no temporary variables used. Nonetheless I can't take credit for this answer as it has been [Neil's idea](https://codegolf.stackexchange.com/questions/127839/swap-the-two-given-indices#comment315239_127842).
[Answer]
# [Common Lisp](http://www.clisp.org/), 42 bytes
*-2 bytes thanks to [@coredump](https://codegolf.stackexchange.com/users/903/coredump).*
```
(lambda(a i j)(rotatef(elt a i)(elt a j)))
```
[Try it online!](https://tio.run/##dU1LCsIwEN3nFI@KMLMQqtbfccY2gZaJlXRU3PTqsUILbty9/6u1He6ZGh@ekhDfm@ElE1eJ10ZI0KJjSr2J@UBeDZPEM@iYObNzP21JCSsqscUOe1Q44IgTzrgwOwp9imIwFKOM62LOf43HrRbV5X4ZKlH9b@UP "Common Lisp – Try It Online")
Quite straight forward, since there is a Common Lisp macro to swap: `rotatef`.
[Answer]
# Javascript ES6, ~~36~~ 34 bytes
```
(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)
```
* *-2 Bytes because the function is altering the array. No need to return the array. Thanks to @Neil*
## Demo
```
f=
(a,m,n)=>(x=a[m],a[m]=a[n],a[n]=x)
let a1=[1,2,3,4], a2=[5,8,9], a3=[11,13,15,3]
f(a1,0,1);
f(a2,0,2);
f(a3,1,2);
console.log(JSON.stringify(a1)); //[2,1,3,4]
console.log(JSON.stringify(a2)); //[9,8,5]
console.log(JSON.stringify(a3)); //[11,15,13,3]
```
[Answer]
# Shenzhen I/O, 735 Bytes
23¥, 810 Power, 48 Lines of Code
```
[traces] 
......................
......................
......................
......................
......................
......................
.14.14.14.............
.94.14.14.............
.A........1C..........
.3554..95556..........
.9554.16..............
.A....................
.2....................
......................
[chip] 
[type] UC6
[x] 4
[y] 2
[code] 
  slx x0
  mov x1 acc
  mov x1 dat
  mov acc x3
  mov dat x3
  mov acc x3
  mov dat x3
[chip] 
[type] UC6
[x] 8
[y] 5
[code] 
  slx x2
  mov x2 x1
  mov x0 dat
  mov x2 x1
  mov x0 acc
  mov x2 x1
  mov dat 
[chip] 
[type] UC4X
[x] 2
[y] 6
[code] 
  slx x0
  mov 0 x3
j:  mov x0 acc
  mov acc x2
  teq acc 0
- jmp j
  mov -999 x1
[chip] 
[type] RAM
[x] 5
[y] 6
```
[![SIO](https://i.stack.imgur.com/HorMB.jpg)](https://i.stack.imgur.com/HorMB.jpg)
DISCLAIMER: Arrays are 0-terminated in this. Arrays are a pain in the ass to work with in Shenzhen I/O otherwise.
I actually made a steam level for this game. You can play it [here.](http://steamcommunity.com/sharedfiles/filedetails/?id=954747779)
EDIT: Aaand I just realized I said that the array in was ordered. Heck.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
iʰ{pᵗz=ᵗ!|}htI&h∋↙I
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFjzc1Vn7cOuE/5mnNlQXPNw6vcoWSCjW1GaUeKplPOroftQ20/P//2iF6GhDHSMdYx2TWB2FaAMdw1gQHW2qY6FjCRExgogYGuoYGusYmuoYg7iG2IWNYPpBwqaowgqxAA "Brachylog – Try It Online")
The process of writing this [generator](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/10753#10753) was fairly clumsy, so there's probably some further golfing to do. I may not have thought to use `i` if I hadn't initially thought I had some use for the value half of the pair it outputs! Takes input as `[array, [m, n]]`.
[Answer]
# [Java 8](http://openjdk.java.net/), 48 bytes
```
(a,b,c)->{int t=a[b];a[b]=a[c];a[c]=t;return a;}
```
Input:
```
int[] a
int b
int c
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
D²è³ǝ¹³è²ǝ
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f5dCmwysObT4@99DOQ5uBrE3H5/7/H22oY6RjrGMSy2XAZQgA "05AB1E – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 28 bytes
```
@(a,n){a(n)=a(flip(n)),a}{2}
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnT7M6USNP0zZRIy0nswDI0tRJrK02qv2fphFtqGOkY6xjEqsDYsVqcgGFTHUsdCzBAsYQAUNDHUNjHUNTIF8n2girqDFI838A "Octave – Try It Online")
Quite satisfied with this one actually :)
Takes input on the form: `f([1,2,3,4],[1,2])`, 1-indexed.
**Explanation:**
```
@(a,n)                         % Anonymous function that takes two 1-dimensional
                               % arrays as input
      {               , }      % Create a cell with two elements
       a(n)=a(flip(n))         % One element are the two number at indices given by
                               % the second input array. This will be a 1x2 array
      {a(n)=a(flip(n)),a}      % Place those two in a cell together with the entire array a
                               % a is now updated, thanks to Octave's inline assignment
      {a(n)=a(flip(n)),a}{2}   % Return the second element
```
[Answer]
## [Jellyfish](https://github.com/iatorm/jellyfish), 7 bytes
```
p
ZRi
i
```
Takes a list and a pair of indices.
[Try it online!](https://tio.run/##y0rNyalMyyzO@P@/gCsqKJMr8///aDMFUwVzBctYrmhDBeNYAA "Jellyfish – Try It Online!")
## Explanation
Jellyfish happens to have a "modify items at indices" function, `Z`, which does exactly what we need.
The two `i`s grab the inputs from STDIN.
`Z` takes as arguments the second input, the reversal function `R`, and the list.
Then `Z` performs the modification, and `p` prints the result.
[Answer]
# R, 38 bytes
```
function(x,a,b){x[c(a,b)]=x[c(b,a)];x}
```
Feels rather long, but I can't get it much shorter. Sadly it requires the explicit returning through `x`, requiring `{}` around the function body. `pryr::f()` doesn't recognise the need for `x` as function argument so doesn't work :/.
[Answer]
# Java 8 + [InverseY](https://github.com/PlutoPowered/InverseY/blob/master/src/main/java/com/gmail/socraticphoenix/inversey/many/Consumer3.java), 27 bytes
```
java.util.Collections::swap
```
Just calls the swap function... this is a method reference of the type `Consumer3<List, Integer, Integer>`.
[Try it online!](https://tio.run/##TVDBTsMwDL3vK3zs0Ig2ygE2NmnaCQmkSvsCk2VVSppEsTs0oX17cQIMoiS23rPfi9PhCW9DNL47vI@2jyExdIKpga1TN6tJHN6c1aAdEsErWg@fk1@QGFnCKdgD9EJVe07Wt0opwNTSVEpB1i54GnqT6qcXSzyDZ8@mNemabIA@MMIaxj/nXXDOaLbSulxmelwVrawALl9r2KaEZ1JIGazmM7iTs5D9KKmEh@l3T25XGp2rXPG/F/qH2p@JTa/CwCrK09n5UiPs5TqlwCYdUZt/gzRi04hHU2/yf2Sp8gvFpVlALDzEUgKxFsGseBm/AA) (header and footer for boilerplate & copy of `Consumer3` interface)
[Answer]
# Swift, ~~111~~ 65 bytes (0-indexed)
Swift is already notorious for being one of the worst code-golf languages, but here is a function ~~that makes use of ternary expressions~~:
```
func t(l:[Int],m:Int,n:Int){var r=l;r[m]=l[n];r[n]=l[m];print(r)}
```
[Check it out!](http://swift.sandbox.bluemix.net/#/repl/594bac0de7b3821b65a0c480)
- **Usage:** `t(l:[1,2,3],m:0,n:1)`.
[Answer]
# [k](http://en.wikipedia.org/wiki/K_(programming_language)) ([kona](https://github.com/kevinlawler/kona)), 13 bytes
```
{x[y]:x@|y;x}
```
Pretty basic, but it works. Ex: 
```
k){x[y]:x@|y;x}[1 2 3 4; 0 1]
2 1 3 4
```
[Answer]
# [Perl 5](https://www.perl.org/), 32 bytes
*-3 bytes thanks to [@Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings)!*
30 bytes of code + `-pa` flags.
```
@F[pop@p,@p]=@F[@p=<>];$_="@F"
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAsS/zu4RRfkFzgU6DgUxNoCOQ4FtjZ2sdYq8bZKDm5K//8bKhgpGCuYKJgqmCmYK1goWCoYGnAZcVkAAA "Perl 5 – Try It Online")
Quite straight forward, using array slices.
[Answer]
# Mathematica, 32 bytes
```
(a=#;a[[{##2}]]=a[[{#3,#2}]];a)&
```
[Answer]
# C, 42 bytes
Modify the array in place with a temp value.
```
f(r,m,n){int*a=r;r=a[m];a[m]=a[n];a[n]=r;}
```
# C, ~~60~~ 58 bytes
A little more interesting, not using any temp value...
```
f(a,m,n)int*a;{a[m]+=a[n];a[n]-=a[m];a[n]*=-1;a[m]-=a[n];}
```
# C, 49 bytes
Using XOR
```
f(a,m,n)int*a;{a[m]^=a[n];a[n]^=a[m];a[m]^=a[n];}
```
[Answer]
# [Julia 0.5](http://julialang.org/), 20 bytes
```
x*t=x[t]=x[t[[2,1]]]
```
[Try it online!](https://tio.run/##dc5BCgIxDAXQdXuKLlP5m7QWdOFJShaCCpWhylCht68ZBmEYMIsPyYNPnp@pXNMY/dAuPTdZIucAFpHxeM2OOpp3pVpDlBkBEUeB09HNBfGwxlFOOOG83leJP2EGR3BCVNbmfxI3bYuknXhrjdE3Nd9zqW2q1L2919v4Ag "Julia 0.5 – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~17~~ 8 bytes
Saved 9 bytes thanks to Leaky Num.
```
@LQ.rUQE
```
[Test it online!](https://pyth.herokuapp.com/?code=%40LQ.rUQE&input=%5B11%2C13%2C15%2C3%5D%0A%281%2C2%29&debug=0)
This is 0-indexed, and the indices are provided as a tuple: `(n, m)`.
**Explanations**
```
@LQ.rUQE
     UQ     # Generate [0, 1, 2, ..., len(input)]
       E    # Get the indices as the tuple (1, 2)
   .r       # Translate each element of UQ to its cyclic successor in E
            # Now the indices are permuted (e.g. [0, 2, 1, ..., len(input)]
@LQ         # For each index, get it's value. Implicit print
```
[Answer]
# Mathematica, 20 bytes
```
#~Permute~Cycles@#2&
```
Pure function taking two arguments in the following 1-indexed (and possibly abusive) format: the second test case `[5,8,9]; 0 2; [9,8,5]` would be called as
```
#~Permute~Cycles@#2& [ {5,8,9} , {{1,3}} ]
```
(spaces are extraneous and just for visible parsing). `Permute` is the builtin function that applies a permutation to a list, and `Cycles[{{a,b}}]` represents the permutation that exchanges the `a`th and `b`th elements of a list and ignores the rest.
[Answer]
# x86 Machine Code, 10 bytes
```
8B 04 8B 87 04 93 89 04 8B C3
```
This is a function written in 32-bit x86 machine code that swaps the values at the specified indices in a given array. The array is [modified in-place](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/4942#4942), and the function does not return a value.
A custom calling convention is used, requiring the function's parameters to be [passed in registers](https://codegolf.meta.stackexchange.com/a/8508/58518):
* The address of the array (pointer to its first element) is passed in the `EBX` register.
* The zero-based index of element A is passed in the `ECX` register.  
(Assumed to be a valid index.)
* The zero-based index of element B is passed in the `EDX` register.  
(Assumed to be a valid index.)
This keeps the size down and complies with all formal requirements, but does mean that the function cannot be easily called from other languages like C. You'd need to call it from another assembly-language program. (You could rewrite it to use *any* input registers, though, without affecting the byte count; there's nothing magical about the ones I chose.)
Ungolfed:
```
8B 04 8B     mov  eax, DWORD PTR [ebx+ecx*4]   ; get value of element A
87 04 93     xchg eax, DWORD PTR [ebx+edx*4]   ; swap element A and element B
89 04 8B     mov  DWORD PTR [ebx+ecx*4], eax   ; store new value for element A
C3           ret                               ; return, with array modified in-place
```
[Answer]
## R, 34 bytes
```
pryr::f(`[<-`(a,c(m,n),a[c(n,m)]))
```
[Answer]
# JavaScript (ES2015), 66 57 49 bytes
A different (alas, longer) approach than previous JavaScript answers
```
(s,h,o,w=s.splice.bind(s))=>w(h,1,...w(o,1,s[h]))
```
Source
```
const swap = (arr, a, b, splice) => {
  splice(a, 1, ...splice(arr[b], 1, arr[a]))
}
```
]