Skip to content

Commit 745ad10

Browse files
authored
add pop!(vector, idx, [default]) (#35513)
1 parent 59ac6d1 commit 745ad10

File tree

4 files changed

+35
-0
lines changed

4 files changed

+35
-0
lines changed

NEWS.md

+1
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ New library features
122122
* `x::Signed % Unsigned` and `x::Unsigned % Signed` are supported for integer bitstypes.
123123
* `signed(unsigned_type)` is supported for integer bitstypes, `unsigned(signed_type)` has been supported.
124124
* `accumulate`, `cumsum`, and `cumprod` now support `Tuple` ([#34654]) and arbitrary iterators ([#34656]).
125+
* `pop!(collection, key, [default])` now has a method for `Vector` to remove an element at an arbitrary index ([#35513]).
125126
* In `splice!` with no replacement, values to be removed can now be specified with an
126127
arbitrary iterable (instead of a `UnitRange`) ([#34524]).
127128
* The `@view` and `@views` macros now support the `a[begin]` syntax that was introduced in Julia 1.4 ([#35289]).

base/array.jl

+16
Original file line numberDiff line numberDiff line change
@@ -1129,6 +1129,22 @@ function pop!(a::Vector)
11291129
return item
11301130
end
11311131

1132+
function pop!(a::Vector, i::Integer)
1133+
x = a[i]
1134+
_deleteat!(a, i, 1)
1135+
x
1136+
end
1137+
1138+
function pop!(a::Vector, i::Integer, default)
1139+
if 1 <= i <= length(a)
1140+
x = @inbounds a[i]
1141+
_deleteat!(a, i, 1)
1142+
x
1143+
else
1144+
default
1145+
end
1146+
end
1147+
11321148
"""
11331149
pushfirst!(collection, items...) -> collection
11341150

base/dict.jl

+3
Original file line numberDiff line numberDiff line change
@@ -576,6 +576,9 @@ end
576576
Delete and return the mapping for `key` if it exists in `collection`, otherwise return
577577
`default`, or throw an error if `default` is not specified.
578578
579+
!!! compat "Julia 1.5"
580+
For `collection::Vector`, this method requires at least Julia 1.5.
581+
579582
# Examples
580583
```jldoctest
581584
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);

test/arrayops.jl

+15
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,21 @@ end
466466
end
467467
@test_throws BoundsError insert!(v, 5, 5)
468468
end
469+
470+
@testset "pop!(::Vector, i, [default])" begin
471+
a = [1, 2, 3, 4]
472+
@test_throws BoundsError pop!(a, 0)
473+
@test pop!(a, 0, "default") == "default"
474+
@test a == 1:4
475+
@test_throws BoundsError pop!(a, 5)
476+
@test pop!(a, 1) == 1
477+
@test a == [2, 3, 4]
478+
@test pop!(a, 2) == 3
479+
@test a == [2, 4]
480+
badpop() = @inbounds pop!([1], 2)
481+
@test_throws BoundsError badpop()
482+
end
483+
469484
@testset "concatenation" begin
470485
@test isequal([fill(1.,2,2) fill(2.,2,1)], [1. 1 2; 1 1 2])
471486
@test isequal([fill(1.,2,2); fill(2.,1,2)], [1. 1; 1 1; 2 2])

0 commit comments

Comments
 (0)