g | x | w | all
Bytes Lang Time Link
068SAKO250326T174843ZAcrimori
074Tcl211201T121811Zsergiol
028Zsh241218T072558Zroblogic
004J241216T034646Zsouth
035Dart241215T112316ZDmytro R
035C# Visual C# Compiler241215T003359Zsergiol
058C# Visual C# Compiler211201T131652Zsergiol
003Uiua231105T190920Zchunes
008Pip xp211015T175705ZDLosc
010BQN211227T115747ZDominic
001MathGolf211202T074520ZKevin Cr
036AWK211201T145946ZPedro Ma
036C++ gcc211201T124231Zsergiol
049Desmos211110T071020ZAiden Ch
006ErrLess211023T081330ZRuan
018Raku211017T172950ZSean
027Clojure211018T162947ZNikoNyrh
030Ruby211019T094405ZDrQuariu
021Factor211015T223721Zchunes
004CJam211015T195126ZLuis Men
042Perl 5211015T203407Zplentyof
007x8616 machine code211018T011247Z640KB
034Pari/GP211018T033318Zalephalp
00405AB1E211017T170221ZKevin Cr
038Javascript211017T160418ZWilliam
205Lean211016T225801Zuser
158Core Maude211017T021452ZChris Bo
034Kotlin211016T210723Zbusukxua
034Icon211016T072203ZGalen Iv
033TIBasic211015T222601ZYouserna
021Wolfram Language Mathematica211015T194240ZMichael
049Python 2211016T042201ZAkshay S
049Python 3211016T112031ZStephen
011Rust211016T085545Zalephalp
033Red211016T071457ZGalen Iv
005stacked211015T225626ZConor O&
031JavaScript211015T151805ZUnmitiga
038C++211015T161210ZUnmitiga
034C clang211015T181113ZNoodle9
099Retina 0.8.2211015T162754ZNeil
014Charcoal211015T160236ZNeil
122BrainFlak211015T154448ZWheat Wi
007Vyxal211015T155207ZAaroneou
032Python 2211015T151159Zpxeger
005APL Dyalog Unicode211015T153850Zovs
005Jelly211015T153150Zcaird co
046PHP211015T153813ZKaddath
039Zsh211015T153652Zpxeger
007Jelly211015T153637Zhyperneu
031R211015T152741Zpajonk
027Java211015T152426ZUnmitiga
020Julia 1.0211015T152224ZMarcMush
056Haskell211015T151116ZWheat Wi
049Python 2211015T150624ZTwilight

SAKO, 68 bytes

PODPROGRAM:(*A)=S(*A,K,O)
CALKOWITE:K,O
C=A(K)
A(K)=A(O)
A(O)=C
WROC

Very simple solution that takes an array (A) and two integers (K, O) as arguments to a subroutine (S()), and swaps them using a temporary variable C.
To make it more interesting I made it spell out SAKO in the subroutine definition.

Interestingly, declaration STRUKTURA isn't needed, as we operate only on given indexes in an array of known type, so specifyin its size isn't obligatory.

Tcl, 74 bytes

proc S {L a b} {lset M $a [lindex [set M $L] $b]
lset M $b [lindex $L $a]}

Try it online!


# [Tcl], 75 bytes
proc S {L a b} {set x [lindex $L $a]
lset L $a [lindex $L $b]
lset L $b $x}

Try it online!

Zsh, 28 bytes

eval $i=$@[j] $j=$@[i]
<<<$@

Assumes i and j are the indices to swap.

Attempt This Online!  33b 34b

J, 4 bytes

C.~<

Input is L f (a b). The function is a dyadic hook.

Attempt This Online!

C.~<
   <   NB. box y
C.~    NB. apply a permutation in cycle form (C.) with the arguments swapped (~)   

C. fills in the incomplete permutation according to the identity permutation, thus, the items are swapped and everything else is left alone.

I suppose if a b could be given as a boxed list, then an improvement could be made by allowing the answer to be C. alone (meaning the input is given as (<a b) f L).

Dart, 35 bytes

(l,a,b)=>[...l]..[a]=l[b]..[b]=l[a]

Try it online! DartPad

Ungolfed:

List<dynamic> s(List<dynamic> l, int a, int b) =>
  [...l] // copy array
    ..[a] = l[b]  // set b value from original to a pos
    ..[b] = l[a]; // and opposite

C# (Visual C# Compiler), 35 bytes

(L,a,b)=>{(L[a],L[b])=(L[b],L[a]);}

Try it online!

based on my own answer, mixed with the lambda idea from the @KevinCruijssen 's idea on his comment there.

C# (Visual C# Compiler), 58 bytes

void f<T>(List<T> L,int a,int b){(L[a],L[b])=(L[b],L[a]);}

Try it online!

Uiua, 3 bytes

⍜⊏⇌

Try it!

0-indexed.

Pip -xp, 8 bytes

aRAba@Rb

Takes input as two command-line arguments: the list, and a list containing the two indices (0-based). Attempt This Online!

Explanation

The -x flag is for taking the arguments as lists rather than strings; the -p flag is for displaying the result as a list rather than concatenated together.

a         ; In the first argument
 RA       ; replace the items at indices given by
   b      ; the second argument
    a     ; with the values in the first argument
     @    ; at indices
      Rb  ; reverse(second argument)

The straightforward version, which takes the indices as separate arguments, comes in at 9 bytes:

a@b::a@ca
   ::      ; Swap
a@b        ; the item in a at index b
     a@c   ; with the item in a at index c
        a  ; Output the new value of a

BQN, 18 10 bytes

Edit: -8 bytes thanks to Razetime

{⌽⌾(𝕨⊸⊏)𝕩}

Try it at BQN online REPL

Probably not the tersest code, but it works, which was no trivial accomplishment for my very limited BQN ability. Now quite short...
Will try to golf-down better as my abilities (gradually) improve. ...thanks to Razetime.

Swap ← {⌽⌾(𝕨⊸⊏)𝕩}          # define Swap function:
                            # list of 2 indices to swap on left = 𝕨
                            # array on right = 𝕩.
                            
         ⌾                  # 'under' = apply function on LHS
                            # to elements specified by RHS  
          (𝕨⊸⊏)            #   RHS: elements of 𝕩 at indices 𝕨
        ⌽                   #   LHS: reverse

MathGolf, 1 byte

µ

Apparently MathGolf has a builtin for this. Came across it in the docs when I was working on another challenge today. ¯\_(ツ)_/¯.

Takes the loose index-inputs before the list.

Try it online.

AWK, 36 bytes

$$(NF-1)+=$$NF-($$NF=$$(NF-1)),NF-=2

Try it online!

Expected input

The input is a list of integers separated by spaces; the last two integers are the indexes of the values that must be swapped:

Input:
3 8 1 4 10 10 10 10 1 6
\_________________/ | |
 List of integers,  | L> Second index
starting index at 1 |
                    L> First index

Output:
10 8 1 4 10 3 10 10
|           |
\___________/
   Swapped

How it works

$$(NF-1)                        We take the integer which index is the value of the second-to-last integer,
        +=                      and add:
          $$NF                  the integer which index is the last integer
              -($$NF            minus itself,
                    =$$(NF-1))  except that it is now the integer which index is the second-to-last integer.
,NF-=2                          And let's remove the last two integers.
                                Phew! It should print the modified input, at last.

It uses this swapping oneliner: a+=b-(b=a).

For better understanding: NF is the variable for the number of fields, i.e, the number of integers in the input. $n is the nth integer in the input, so $NF is the last integer, and $(NF-1) the second-to-last integer. $$NF equals $($NF), that is the integer which index is the last integer.

NF-=2 reduces the number of fields by two, ignoring the two indexes.

C++ (gcc), 36 bytes

#define f(a,i,j)std::swap(a[i],a[j])

Try it online!

Desmos, 49 bytes

l=[1...L.length]
f(L,a,b)=\{l=a:L[b],l=b:L[a],L\}

Try It On Desmos!

Try It On Desmos! - Prettified

Surprisingly readable (if you know a bit of Desmos) even after I code golfed it.

Python Equivalent (switching to 0-based)

def f(L,a,b):
    returnList = []
    for l in range(len(L)):
        if l == a:
            returnList.append(L[b])
        elif l == b:
            returnList.append(L[a])
        else:
            returnList.append(L[l])
    return returnList

ErrLess, 6 bytes

0m:r.M

A macro.

Explanation

0 { Push a 0 to the stack to identify the macro } 
m { Start macro definition }
: { (L a b) -> (L (a b)) }
r { Rotate }
. { Halt (Return) }
M { End macro definition }

You can test it with the following program:

0m
 :r.
M

{ Test cases: }

1,2x3x4x5x6x7x8x9xax 3 7
0" # a? { Outputs "(1 2 3 8 5 6 7 4 9 10)" and a newline }

3,8x1x4xaxaxaxax 0 5
0" # a? { Outputs "(10 8 1 4 10 3 10 10)" and a newline }

5,1x4x2x3x 0 4
0" # a? { Outputs "(3 1 4 2 5)" and a newline }

5,6x 0 1
0" # a? { Outputs "(6 5)" and a newline }

2,2x2x 0 1
0" # a? { Outputs "(2 2 2)" and a newline }
.

Try it online!

Raku, 19 18 bytes

{@^a[@^i].=rotate}

Try it online!

0-based indexing. Modifies the list in-place. Takes the indices as a two-element list.

Edit: rotate has the same effect as reverse and is one character shorter. D'oh!

Clojure, 27 bytes

#(assoc % %2(% %3)%3(% %2))

The first argument % is a vector of numbers (not a list!) so that we don't need to use the function nth.

Edit: TIO

Edit 2: And actually you cannot assoc a list anyway.

Ruby, 30 bytes

->(l,a,b){l[a],l[b]=l[b],l[a]}

Mutates the input in-place. Direct port of @pxeger's approach including the link below:

Attempt This Online!

Factor, 21 bytes

[ [ exchange ] keep ]

Try it online!

It's almost a built-in, but exchange has stack effect ( m n seq -- ) so we need keep to actually keep the sequence around on the data stack. 0-indexed.

CJam, 4 bytes

{e\}

Code block (analogous to a function) that pops three elements from the stack: L, a, b, and pushes the swapped version of L. Indices a, b are 0-based.

Try it online!

Explanation

{  }  e# Define code block
 e\   e# Swap elements in array

Header:

q     e# Read all input as an unevaluated string, and push it to the stack
 ~    e# Evaluate string. Gives an array and two numbers, that are pushed

Footer:

~     e# Execute block
 p    e# Print string representation of the top of the stack

Perl 5, 42 bytes

Updated TIO link to show positive indices only per challenge instructions (thanks, Kevin!)

sub a{($a,$b,$l)=@_;@$l[$a,$b]=@$l[$b,$a]}

Try it online!

Takes arguments as (first index, second index, 0-bound array). Mutates array in-place. Works with arrays containing any valid values, not just positive integers!

x86-16 machine code, 7 bytes

00000000: 8a01 8600 8801 c3                        .......

Listing

8A 01   MOV  AL, BYTE PTR[BX][DI]       ; put 'b' value into AL 
86 00   XCHG AL, BYTE PTR[BX][SI]       ; swap 'b' value with 'a' position 
88 01   MOV  BYTE PTR[BX][DI], AL       ; put 'a' value into 'b' position 
C3      RET                             ; return to caller 

Input \$L\$ at [BX], indices \$a\$ in SI, \$b\$ in DI, 0-based.

A test with our old friend DOS DEBUG:

enter image description here

Pari/GP, 34 bytes

f(l,a,b)=[l[a],l[b]]=[l[b],l[a]];l

Try it online!

1-indexed

05AB1E, 4 bytes

è¹Rǝ

Since no one posted an 05AB1E answer yet and it's been a couple of days, I'm gonna post my prepared 4-byter.

First input is a pair of indices \$[a,b]\$, second input is the list \$L\$.

Try it online or verify all test cases.

Explanation:

è    # Index the first (implicit) input into the second (implicit) input-list
 ¹   # Push the first input-indices again
  R  # Reverse them
   ǝ # Insert the values at those reversed indices into the (implicit) second input-list
     # (after which the result is output implicitly)

Javascript 38 bytes

(l,a,b)=>(l[a]=[l[b],l[b]=l[a]][0])&&l

Lean, 211 205 bytes

Helper:

notation `L`:=list ℕ
structure R:=m::(A:L)(B:ℕ)(C:L)
def r:L->L->ℕ->R
|p(h::t)0:=R.m p h t
|p(h::t)(n+1):=r(p++[h])t n
|_[]_:=R.m[]0[]

Actual function:

λl a b,let f:=r[]l a,z:=r[]f.C(b-a-1)in f.A++z.B::z.A++f.B::z.C

Try it online!

There's got to be a way to make product types and define type aliases easily, but I couldn't find it.

Core Maude, 158 bytes

mod S is pr ARRAY{Nat,Nat0}*(sort Array{Nat,Nat0}to A). var I J X Y : Nat . op
s : A Nat Nat -> A . eq s(A:A,I,J)= insert(I,A:A[J],insert(J,A:A[I],A:A)). endm

Example Session

             \||||||||||||||||||/
           --- Welcome to Maude ---
             /||||||||||||||||||\
         Maude 3.1 built: Oct 12 2020 20:12:31
         Copyright 1997-2020 SRI International
               Sat Oct 16 22:01:13 2021
Maude> mod S is pr ARRAY{Nat,Nat0}*(sort Array{Nat,Nat0}to A). var I J X Y : Nat . op
> s : A Nat Nat -> A . eq s(A:A,I,J)= insert(I,A:A[J],insert(J,A:A[I],A:A)). endm
Maude> red s(0 |-> 1 ; 1 |-> 2 ; 2 |-> 3 ; 3 |-> 4 ; 4 |-> 5 ; 5 |-> 6 ; 6 |-> 7 ;
>       7 |-> 8 ; 8 |-> 9 ; 9 |-> 10, 3, 7) .
result A: 0 |-> 1 ; 1 |-> 2 ; 2 |-> 3 ; 3 |-> 8 ; 4 |-> 5 ; 5 |-> 6 ; 6 |-> 7 ;
    7 |-> 4 ; 8 |-> 9 ; 9 |-> 10
Maude> red s(0 |-> 3 ; 1 |-> 8 ; 2 |-> 1 ; 3 |-> 4 ; 4 |-> 10 ; 5 |-> 10 ; 6 |-> 10 ;
>       7 |-> 10, 0, 5) .
result A: 0 |-> 10 ; 1 |-> 8 ; 2 |-> 1 ; 3 |-> 4 ; 4 |-> 10 ; 5 |-> 3 ; 6 |->
    10 ; 7 |-> 10
Maude> red s(0 |-> 5 ; 1 |-> 1 ; 2 |-> 4 ; 3 |-> 2 ; 4 |-> 3, 0, 4) .
result A: 0 |-> 3 ; 1 |-> 1 ; 2 |-> 4 ; 3 |-> 2 ; 4 |-> 5
Maude> red s(0 |-> 5 ; 1 |-> 6, 0, 1) .
result A: 0 |-> 6 ; 1 |-> 5
Maude> red s(0 |-> 2 ; 1 |-> 2 ; 2 |-> 2, 0, 1) .
result A: 0 |-> 2 ; 1 |-> 2 ; 2 |-> 2

Ungolfed

mod S is
    pr ARRAY{Nat,Nat0} * (sort Array{Nat,Nat0} to A).
    var I J X Y : Nat .
    op s : A Nat Nat -> A .
    eq s(A:A, I, J) = insert(I, A:A[J], insert(J, A:A[I], A:A)) .
endm

The answer is obtained by reducing the function s with the list, given as a Maude array (e.g., 0 |-> 1 ; 1 |-> 2 for [1, 2]), and the two indices, zero-indexed.

Maude does have lists (e.g., 0 1 for the same list [1, 2]), but this is one case where it's actually shorter to use arrays (which are generally very verbose) because we don't need to use an array literal syntax in the code, and because we need indexing. The FAQ says it's allowed to accept input as either an array or a list.

Kotlin, 34 bytes

{l,x,y->l[x]=l[y].also{l[y]=l[x]}}

Ungolfed:

{ l, x, y ->
    l[x] = l[y].also { l[y] = l[x] }
}

This answer is a bit of an idiom in Kotlin.

Any#also() basically executes the given function, but then returns the receiver. In this case, the outer l[y] is evaluated, then .also() runs the lambda { l[y] = l[x] }, and returns the old value of l[y].

Try it online!

Icon, 43 34 bytes

-9 bytes thanks to Kevin Cruijssen

procedure s(l,a,b)
l[a]:=:l[b]
end

Try it online!

1-indexed

TI-Basic, 39 33 bytes

Prompt L,A,B
ʟL(A→X
ʟL(B→ʟL(A
X→ʟL(B
ʟL

-6 bytes thanks to MarcMush.

Input indices are 1-based. Output is stored in Ans and is displayed.

Wolfram Language (Mathematica), 24 21 bytes

1-based indices, input is a list and a tuple of indices to reverse

Reverse~SubsetMap~##&

Try it online!

-3 bytes thanks to att.

Python 2, 52 49 bytes

(longer than the approach by @pxeger, but doesn't mutate in-place

lambda a,b,l:l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:]

Try it Online!

EDIT: Thanks @Stephen Universe for saving me few bytes!


56 bytes by using list.pop and list.insert:

def f(a,b,l):l.insert(b,l.pop(a)),l.insert(a,l.pop(b-1))

Try it online!

Python 3, 49 bytes

lambda l,a,b:l[:a]+[l[b]]+l[a+1:b]+[l[a]]+l[b+1:]

Try it online!

The very simple way.

Rust, 11 bytes

<[_]>::swap

Modify the input in-place.

Try it online!

Red, 33 bytes

func[l a b][swap at l a at l b l]

Try it online!

1-indexed

stacked, 5 bytes

$exch

Try it online!

You can remove the $ if input is allowed to be taken from the stack for 4 bytes. Convenient builtin to be sure.

22 bytes

[@j@i[i j nswap]apply]

Function. nswap performs a stack operation of swapping the ith and jth members, so we simply pop i and j and treat the stack at the top of the stack as the stack for nswap.

JavaScript, 31 bytes

l=>a=>b=>l[a]^=l[b]^(l[b]=l[a])

Only works for integers.

Try it online!

Thanks to Arnauld.

JavaScript, 32 bytes

l=>a=>b=>[l[a],l[b]]=[l[b],l[a]]

Try it online!

C++, 51 46 38 bytes

#define f(a,i,j)a[i]^=a[j]^(a[j]=a[i])

Saved 5 bytes thanks to Kevin Cruijssen.

Saved 8 bytes thanks to AZTECCO.

Try it online!

C (clang), 34 bytes

f(*a,i,j){a[i]^=a[j]^(a[j]=a[i]);}

Try it online!

Port of Unmitigated's C++ answer

Retina 0.8.2, 99 bytes

2`\d+
$*
1*(,1*);
$1,$&
(?<=(?=.*;(?<-2>\d+,)*(\d+))(1)*,(?(4)$)(?<-4>1)*(,1*)?;(\d+,)*)\d+
$1
.*;

Try it online! Link includes test cases. Takes input in the form a,b;L. Explanation:

2`\d+
$*

Convert the indices to unary.

1*(,1*);
$1,$&

Make a second copy of b so that we now have b,a,b;L.

(?<=(?=.*;(?<-2>\d+,)*(\d+))(1)*,(?(4)$)(?<-4>1)*(,1*)?;(\d+,)*)\d+
$1

Match an integer in L, with index $#4 equalling either a or b (using a .NET balancing group), then match the other index in $#2, and match the integer at that index as the replacement for this integer (also using a .NET balancing group).

.*;

Delete a and b.

Charcoal, 14 bytes

IEθ⎇№ηκ§θ⁻Σηκι

Try it online! Link is to verbose version of code. Takes the 0-indexed indices as a 2-element array. Explanation:

  θ             Input array
 E              Map over elements
    №           Count of
      κ         Current index in
     η          Input indices
   ⎇            If found then
        θ       Input array
       §        Indexed by
           η    Input indices
          Σ     Take the sum
         ⁻      Minus
            κ   Current index
             ι  Else current element
I               Cast to string
                Implicitly print

Brain-Flak, 122 bytes

(([{}]{()<({}[()]<({}<>)<>>)>}{})<(({}({}))([{}]{})<{({}()<<>({}<>)>)}{}>)>())<>({}<<>{({}[()]<({}<>)<>>)}{}>){<>({}<>)}{}

Try it online!

Works with all integers, 138 bytes

(([{}]{()<({}[()]<({}<>)<>>)>}{})<(({}({}))([{}]{})<{({}()<<>({}<>)>)}{}>)>())<>({}<<>{({}[()]<({}<>)<>>)}{}>)<>([]){({}[()]<({}<>)<>>)}<>

Try it online!

The difference here is that while the first uses

{<>({}<>)}{}

To pull all the items from the off stack onto the on stack this one has to use

<>({}){({}[()]<({}<>)<>>)}<>

The first one pulls until it hits a zero and then stops, so this will fail to produce the correct result when there is a zero before the first swapped value. The second checks the height and pulls that many times, thus it will work for any list.

Vyxal, 7 bytes

İṘZ(n÷Ȧ

Try it Online!

This could almost certainly be a bit smaller, but I got smol brain and can't think of a good way to swap values.

Explanation:

İ        # Get the values at the indexes
 Ṙ       # Reverse the values
  Z      # Zip the values with the new indexes
   (n    # For each value/index pair:
     ÷   #  Split the value/index
      Ȧ  #  Put the value at that index

Python 2, 32 bytes

def f(a,b,l):l[a],l[b]=l[b],l[a]

Attempt This Online!

Mutates the input in-place.


26 bytes with a NumPy array:

def f(l,a):l[a[::-1]]=l[a]

Try it online!

APL (Dyalog Unicode), 5 bytes

1-indexed. Reverse the sublist at the indices given by the second input of the first input.

⌽@⎕⊢⎕

Try it online!

Jelly, 7 5 bytes

œPżịF

Try it online!

Takes indexes as 1 indexed and reversed (so [b, a]), the Footer on TIO does this for you.

How it works

œPżịF - Main link. Takes indices I on the left, array A on the right
œP    - Partition A at the indices in I, not keeping the borders
   ị  - Retrieve the elements of A at the indices in I; [A[b], A[a]]
  ż   - Zip together
    F - Flatten

PHP, 46 bytes

fn(&$a,$i,$j)=>[$a[$i],$a[$j]]=[$a[$j],$a[$i]]

Try it online!

changes the array in place, 0 indexing

My first shot was with list, but PHP has array destructuring since 7.1, so it ends up like the JS answer with lots of dollars (money money money!)

Zsh, 39 bytes

eval "t=$`<i`;`<i`=$`<j`;`<j`=$"t
<<<$@

Attempt This Online!

Takes the array on the command line, with the two indices in files called i and j.

A bit of quote trickery to avoid escapes.

Jelly, 7 bytes

,U$yJ}ị

Try It Online!

A totally different Jelly 7-byter, so I figured I'd post this too. This is 1-indexed.

,U$yJ}ị    Main link; take indices on the left
,U$        Pair the indices with the reverse of itself ([[a, b], [b, a]])
   y       Apply this as a translation to
    J}     The indices of the right list (J takes a list of length L and returns [1, 2, ..., L])
      ị    Index back into the original list

R, 31 bytes

Or R>=4.1, 24 bytes by replacing the word function with \.

function(L,A){L[A]=L[rev(A)];L}

Try it online!

Takes input as a vector and a vector of two 1-based indices.

Java, 27 bytes

java.util.Collections::swap

Try it online!

Julia 1.0, 20 bytes

L*i=L[i]=L[i[[2,1]]]

Try it online!

1-indexed

expects L*[a,b] and mutates L

Haskell, 56 bytes

(?)=splitAt
(x!y)z|(q,d:e)<-y?z,(a,b:c)<-x?q=a++d:c++b:e

Try it online!

splitAt breaks the list into two parts at the particular index. This is useful because unlike (!!) we can get all the parts first.

To start we split at the second element, then the first. Splitting at the second first means we don't have to do extra arithmetic do calculate the offset which is required if we split at the first.

We use a pattern match to then get the first element of various pieces.

Python 2, 49 bytes

lambda a,b,c:a[:b]+[a[c]]+a[b+1:c]+[a[b]]+a[c+1:]

Try it online!