pop!(collection)

pop!(collection) -> item

Remove the last item in collection and return it.

julia> A=[1, 2, 3, 4, 5, 6]
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> pop!(A)
6

julia> A
5-element Array{Int64,1}:
 1
 2
 3
 4
 5

Examples

julia> b = [3, 4, 5]
       pop!(b)
5
julia> a = [1, 2]
       push!(a, 3)
       pop!(a)
3
julia> foo = [1,2,3];

julia> pop!(foo)
3

julia> foo
2-element Array{Int64,1}:
 1
 2

Associative collections

julia> dict = {"A"=>1, "B"=>2, "C"=>3, "D"=>4};

julia> pop!(dict,"A")
1

julia> pop!(dict,"E")
ERROR: key not found: "E"
 in pop! at dict.jl:646

julia> pop!(dict,"E",42)
42

julia> dict
Dict{Any,Any} with 3 entries:
 "B" => 2
 "C" => 3
 "D" => 4
  1. Delete and return the value for a key in a dictionary:

    julia> dict = Dict("apple" => 5, "banana" => 10, "orange" => 8);
    julia> pop!(dict, "banana")
    10

    This example removes the mapping for the key "banana" from the dictionary dict and returns its corresponding value.

  2. Handle missing keys with a default value:

    julia> dict = Dict("apple" => 5, "banana" => 10, "orange" => 8);
    julia> pop!(dict, "grape", 0)
    0

    In this case, the key "grape" is not present in the dictionary. By providing a default value of 0, the function returns the default value instead of throwing an error.

  3. Throw an error when key is not found and default is not specified:
    julia> dict = Dict("apple" => 5, "banana" => 10, "orange" => 8);
    julia> pop!(dict, "grape")
    ERROR: KeyError: key "grape" not found

    If the key "grape" is not found in the dictionary and no default value is provided, the function throws a KeyError indicating that the key was not found.

Common mistake example:

julia> dict = Dict("apple" => 5, "banana" => 10, "orange" => 8);
julia> pop!(dict, "kiwi", "not found")
ERROR: KeyError: key "kiwi" not found

In this example, the default value "not found" is provided to handle the case when the key is not found. However, since the key does not exist in the dictionary, the function still throws a KeyError. It's important to note that the default value is only used if the key is not found.

See Also

append!, delete!, deleteat!, empty!, endof, filter, filter!, gc, get!, getkey, haskey, insert!, isempty, keys, map, map!, merge, merge!, pop!, prepend!, push!, reduce, resize!, shift!, splice!, unshift!, values,

User Contributed Notes

Add a Note

The format of note supported is markdown, use triple backtick to start and end a code block.

*Required Field
Details

Checking you are not a robot: