Sequential iteration is implemented by theiterate function. The generalfor loop:
for i in iter # or "for i = iter" # bodyendis translated into:
next = iterate(iter)while next !== nothing (i, state) = next # body next = iterate(iter, state)endThestate object may be anything, and should be chosen appropriately for each iterable type. See themanual section on the iteration interface for more details about defining a custom iterable type.
Base.iterate —Functioniterate(iter [, state]) -> Union{Nothing, Tuple{Any, Any}}Advance the iterator to obtain the next element. If no elements remain,nothing should be returned. Otherwise, a 2-tuple of the next element and the new iteration state should be returned.
Base.IteratorSize —TypeIteratorSize(itertype::Type) -> IteratorSizeGiven the type of an iterator, return one of the following values:
SizeUnknown() if the length (number of elements) cannot be determined in advance.HasLength() if there is a fixed, finite length.HasShape{N}() if there is a known length plus a notion of multidimensional shape (as for an array). In this caseN should give the number of dimensions, and theaxes function is valid for the iterator.IsInfinite() if the iterator yields values forever.The default value (for iterators that do not define this function) isHasLength(). This means that most iterators are assumed to implementlength.
This trait is generally used to select between algorithms that pre-allocate space for their result, and algorithms that resize their result incrementally.
julia> Base.IteratorSize(1:5)Base.HasShape{1}()julia> Base.IteratorSize((2,3))Base.HasLength()sourceBase.IteratorEltype —TypeIteratorEltype(itertype::Type) -> IteratorEltypeGiven the type of an iterator, return one of the following values:
EltypeUnknown() if the type of elements yielded by the iterator is not known in advance.HasEltype() if the element type is known, andeltype would return a meaningful value.HasEltype() is the default, since iterators are assumed to implementeltype.
This trait is generally used to select between algorithms that pre-allocate a specific type of result, and algorithms that pick a result type based on the types of yielded values.
julia> Base.IteratorEltype(1:5)Base.HasEltype()sourceFully implemented by:
AbstractRangeUnitRangeTupleNumberAbstractArrayBitSetIdDictDictWeakKeyDictEachLineAbstractStringSetPairNamedTupleBase.OrdinalRange —TypeOrdinalRange{T, S} <: AbstractRange{T}Supertype for ordinal ranges with elements of typeT with spacing(s) of typeS. The steps should be always-exact multiples ofoneunit, andT should be a "discrete" type, which cannot have values smaller thanoneunit. For example,Integer orDate types would qualify, whereasFloat64 would not (since this type can represent values smaller thanoneunit(Float64).UnitRange,StepRange, and other types are subtypes of this.
Base.AbstractUnitRange —TypeAbstractUnitRange{T} <: OrdinalRange{T, T}Supertype for ranges with a step size ofoneunit(T) with elements of typeT.UnitRange and other types are subtypes of this.
Base.StepRange —TypeStepRange{T, S} <: OrdinalRange{T, S}Ranges with elements of typeT with spacing of typeS. The step between each element is constant, and the range is defined in terms of astart andstop of typeT and astep of typeS. NeitherT norS should be floating point types. The syntaxa:b:c withb != 0 anda,b, andc all integers creates aStepRange.
Examples
julia> collect(StepRange(1, Int8(2), 10))5-element Vector{Int64}: 1 3 5 7 9julia> typeof(StepRange(1, Int8(2), 10))StepRange{Int64, Int8}julia> typeof(1:3:6)StepRange{Int64, Int64}sourceBase.UnitRange —TypeUnitRange{T<:Real}A range parameterized by astart andstop of typeT, filled with elements spaced by1 fromstart untilstop is exceeded. The syntaxa:b witha andb bothIntegers creates aUnitRange.
Examples
julia> collect(UnitRange(2.3, 5.2))3-element Vector{Float64}: 2.3 3.3 4.3julia> typeof(1:10)UnitRange{Int64}sourceBase.LinRange —TypeLinRange{T,L}A range withlen linearly spaced elements between itsstart andstop. The size of the spacing is controlled bylen, which must be anInteger.
Examples
julia> LinRange(1.5, 5.5, 9)9-element LinRange{Float64, Int64}: 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0, 5.5Compared to usingrange, directly constructing aLinRange should have less overhead but won't try to correct for floating point errors:
julia> collect(range(-0.1, 0.3, length=5))5-element Vector{Float64}: -0.1 0.0 0.1 0.2 0.3julia> collect(LinRange(-0.1, 0.3, 5))5-element Vector{Float64}: -0.1 -1.3877787807814457e-17 0.09999999999999999 0.19999999999999998 0.3See alsoLogrange for logarithmically spaced points.
Base.isempty —Functionisempty(collection) -> BoolDetermine whether a collection is empty (has no elements).
isempty(itr) may consume the next element of a stateful iteratoritr unless an appropriateBase.isdone(itr) method is defined. Stateful iteratorsshould implementisdone, but you may want to avoid usingisempty when writing generic code which should support any iterator type.
Examples
julia> isempty([])truejulia> isempty([1 2 3])falsesourceBase.isdone —Functionisdone(itr, [state]) -> Union{Bool, Missing}This function provides a fast-path hint for iterator completion. This is useful for stateful iterators that want to avoid having elements consumed if they are not going to be exposed to the user (e.g. when checking for done-ness inisempty orzip).
Stateful iterators that want to opt into this feature should define anisdone method that returns true/false depending on whether the iterator is done or not. Stateless iterators need not implement this function.
If the result ismissing, callers may go ahead and computeiterate(x, state) === nothing to compute a definite answer.
Base.empty! —Functionempty!(c::Channel)Empty a Channelc by callingempty! on the internal buffer. Return the empty channel.
empty!(collection) -> collectionRemove all elements from acollection.
Examples
julia> A = Dict("a" => 1, "b" => 2)Dict{String, Int64} with 2 entries: "b" => 2 "a" => 1julia> empty!(A);julia> ADict{String, Int64}()sourceBase.checked_length —FunctionBase.checked_length(r)Calculateslength(r), but may check for overflow errors where applicable when the result doesn't fit intoUnion{Integer(eltype(r)),Int}.
Fully implemented by:
AbstractRangeUnitRangeTupleNumberAbstractArrayBitSetIdDictDictWeakKeyDictAbstractStringSetNamedTupleBase.in —Functionin(item, collection) -> Bool∈(item, collection) -> BoolDetermine whether an item is in the given collection, in the sense that it is== to one of the values generated by iterating over the collection. Can equivalently be used with infix syntax:
item in collectionitem ∈ collectionReturn aBool value, except ifitem ismissing orcollection containsmissing but notitem, in which casemissing is returned (three-valued logic, matching the behavior ofany and==). Some collections follow a slightly different definition. For example,Sets check whether the itemisequal to one of the elements;Dicts look forkey=>value pairs, and thekey is compared usingisequal.
To test for the presence of a key in a dictionary, usehaskey ork in keys(dict). For the collections mentioned above, the result is always aBool.
When broadcasting within.(items, collection) oritems .∈ collection, bothitems andcollection are broadcasted over, which is often not what is intended. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each value in collectionitems isin the value at the corresponding position incollection. To get a vector indicating whether each value initems is incollection, wrapcollection in a tuple or aRef like this:in.(items, Ref(collection)) oritems .∈ Ref(collection).
See also:∉,insorted,contains,occursin,issubset.
Examples
julia> a = 1:3:201:3:19julia> 4 in atruejulia> 5 in afalsejulia> missing in [1, 2]missingjulia> 1 in [2, missing]missingjulia> 1 in [1, missing]truejulia> missing in Set([1, 2])falsejulia> (1=>missing) in Dict(1=>10, 2=>20)missingjulia> [1, 2] .∈ [2, 3]2-element BitVector: 0 0julia> [1, 2] .∈ ([2, 3],)2-element BitVector: 0 1sourceBase.:∉ —Function∉(item, collection) -> Bool∌(collection, item) -> BoolNegation of∈ and∋, i.e. checks thatitem is not incollection.
When broadcasting withitems .∉ collection, bothitems andcollection are broadcasted over, which is often not what is intended. For example, if both arguments are vectors (and the dimensions match), the result is a vector indicating whether each value in collectionitems is not in the value at the corresponding position incollection. To get a vector indicating whether each value initems is not incollection, wrapcollection in a tuple or aRef like this:items .∉ Ref(collection).
Examples
julia> 1 ∉ 2:4truejulia> 1 ∉ 1:3falsejulia> [1, 2] .∉ [2, 3]2-element BitVector: 1 1julia> [1, 2] .∉ ([2, 3],)2-element BitVector: 1 0sourceBase.hasfastin —FunctionBase.hasfastin(T)Determine whether the computationx ∈ collection wherecollection::T can be considered as a "fast" operation (typically constant or logarithmic complexity). The definitionhasfastin(x) = hasfastin(typeof(x)) is provided for convenience so that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types.
The default forhasfastin(T) istrue for subtypes ofAbstractSet,AbstractDict andAbstractRange andfalse otherwise.
Base.eltype —Functioneltype(type)Determine the type of the elements generated by iterating a collection of the giventype. For dictionary types, this will be aPair{KeyType,ValType}. The definitioneltype(x) = eltype(typeof(x)) is provided for convenience so that instances can be passed instead of types. However the form that accepts a type argument should be defined for new types.
Examples
julia> eltype(fill(1f0, (2,2)))Float32julia> eltype(fill(0x1, (2,2)))UInt8sourceBase.indexin —Functionindexin(a, b)Return an array containing the first index inb for each value ina that is a member ofb. The output array containsnothing wherevera is not a member ofb.
Examples
julia> a = ['a', 'b', 'c', 'b', 'd', 'a'];julia> b = ['a', 'b', 'c'];julia> indexin(a, b)6-element Vector{Union{Nothing, Int64}}: 1 2 3 2 nothing 1julia> indexin(b, a)3-element Vector{Union{Nothing, Int64}}: 1 2 3sourceBase.unique —Functionunique(A::AbstractArray; dims::Int)Return unique regions ofA along dimensiondims.
Examples
julia> A = map(isodd, reshape(Vector(1:8), (2,2,2)))2×2×2 Array{Bool, 3}:[:, :, 1] = 1 1 0 0[:, :, 2] = 1 1 0 0julia> unique(A)2-element Vector{Bool}: 1 0julia> unique(A, dims=2)2×1×2 Array{Bool, 3}:[:, :, 1] = 1 0[:, :, 2] = 1 0julia> unique(A, dims=3)2×2×1 Array{Bool, 3}:[:, :, 1] = 1 1 0 0sourceunique(f, itr)Return an array containing one value fromitr for each unique value produced byf applied to elements ofitr.
Examples
julia> unique(x -> x^2, [1, -1, 3, -3, 4])3-element Vector{Int64}: 1 3 4This functionality can also be used to extract theindices of the first occurrences of unique elements in an array:
julia> a = [3.1, 4.2, 5.3, 3.1, 3.1, 3.1, 4.2, 1.7];julia> i = unique(i -> a[i], eachindex(a))4-element Vector{Int64}: 1 2 3 8julia> a[i]4-element Vector{Float64}: 3.1 4.2 5.3 1.7julia> a[i] == unique(a)truesourceunique(itr)Return an array containing only the unique elements of collectionitr, as determined byisequal andhash, in the order that the first of each set of equivalent elements originally appears. The element type of the input is preserved.
See also:unique!,allunique,allequal.
Examples
julia> unique([1, 2, 6, 2])3-element Vector{Int64}: 1 2 6julia> unique(Real[1, 1.0, 2])2-element Vector{Real}: 1 2sourceBase.unique! —Functionunique!(A::AbstractVector)Remove duplicate items as determined byisequal andhash, then return the modifiedA.unique! will return the elements ofA in the order that they occur. If you do not care about the order of the returned data, then calling(sort!(A); unique!(A)) will be much more efficient as long as the elements ofA can be sorted.
Examples
julia> unique!([1, 1, 1])1-element Vector{Int64}: 1julia> A = [7, 3, 2, 3, 7, 5];julia> unique!(A)4-element Vector{Int64}: 7 3 2 5julia> B = [7, 6, 42, 6, 7, 42];julia> sort!(B); # unique! is able to process sorted data much more efficiently.julia> unique!(B)3-element Vector{Int64}: 6 7 42sourceunique!(f, A::AbstractVector)Selects one value fromA for each unique value produced byf applied to elements ofA, then return the modified A.
Examples
julia> unique!(x -> x^2, [1, -1, 3, -3, 4])3-element Vector{Int64}: 1 3 4julia> unique!(n -> n%3, [5, 1, 8, 9, 3, 4, 10, 7, 2, 6])3-element Vector{Int64}: 5 1 9julia> unique!(iseven, [2, 3, 5, 7, 9])2-element Vector{Int64}: 2 3sourceBase.allunique —Functionallunique(itr) -> Boolallunique(f, itr) -> BoolReturntrue if all values fromitr are distinct when compared withisequal. Or if all of[f(x) for x in itr] are distinct, for the second method.
Note thatallunique(f, itr) may callf fewer thanlength(itr) times. The precise number of calls is regarded as an implementation detail.
allunique may use a specialized implementation when the input is sorted.
See also:unique,issorted,allequal.
Examples
julia> allunique([1, 2, 3])truejulia> allunique([1, 2, 1, 2])falsejulia> allunique(Real[1, 1.0, 2])falsejulia> allunique([NaN, 2.0, NaN, 4.0])falsejulia> allunique(abs, [1, -1, 2])falsesourceBase.allequal —Functionallequal(itr) -> Boolallequal(f, itr) -> BoolReturntrue if all values fromitr are equal when compared withisequal. Or if all of[f(x) for x in itr] are equal, for the second method.
Note thatallequal(f, itr) may callf fewer thanlength(itr) times. The precise number of calls is regarded as an implementation detail.
Examples
julia> allequal([])truejulia> allequal([1])truejulia> allequal([1, 1])truejulia> allequal([1, 2])falsejulia> allequal(Dict(:a => 1, :b => 1))falsejulia> allequal(abs2, [1, -1])truesourceBase.reduce —Methodreduce(op, itr; [init])Reduce the given collectionitr with the given binary operatorop. If provided, the initial valueinit must be a neutral element forop that will be returned for empty collections. It is unspecified whetherinit is used for non-empty collections.
For empty collections, providinginit will be necessary, except for some special cases (e.g. whenop is one of+,*,max,min,&,|) when Julia can determine the neutral element ofop.
Reductions for certain commonly-used operators may have special implementations, and should be used instead:maximum(itr),minimum(itr),sum(itr),prod(itr),any(itr),all(itr). There are efficient methods for concatenating certain arrays of arrays by callingreduce(vcat, arr) orreduce(hcat, arr).
The associativity of the reduction is implementation dependent. This means that you can't use non-associative operations like- because it is undefined whetherreduce(-,[1,2,3]) should be evaluated as(1-2)-3 or1-(2-3). Usefoldl orfoldr instead for guaranteed left or right associativity.
Some operations accumulate error. Parallelism will be easier if the reduction can be executed in groups. Future versions of Julia might change the algorithm. Note that the elements are not reordered if you use an ordered collection.
Examples
julia> reduce(*, [2; 3; 4])24julia> reduce(*, Int[]; init=1)1sourceBase.reduce —Methodreduce(f, A::AbstractArray; dims=:, [init])Reduce 2-argument functionf along dimensions ofA.dims is a vector specifying the dimensions to reduce, and the keyword argumentinit is the initial value to use in the reductions. For+,*,max andmin theinit argument is optional.
The associativity of the reduction is implementation-dependent; if you need a particular associativity, e.g. left-to-right, you should write your own loop or consider usingfoldl orfoldr. See documentation forreduce.
Examples
julia> a = reshape(Vector(1:16), (4,4))4×4 Matrix{Int64}: 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16julia> reduce(max, a, dims=2)4×1 Matrix{Int64}: 13 14 15 16julia> reduce(max, a, dims=1)1×4 Matrix{Int64}: 4 8 12 16sourceBase.foldl —Methodfoldl(op, itr; [init])Likereduce, but with guaranteed left associativity. If provided, the keyword argumentinit will be used exactly once. In general, it will be necessary to provideinit to work with empty collections.
See alsomapfoldl,foldr,accumulate.
Examples
julia> foldl(=>, 1:4)((1 => 2) => 3) => 4julia> foldl(=>, 1:4; init=0)(((0 => 1) => 2) => 3) => 4julia> accumulate(=>, (1,2,3,4))(1, 1 => 2, (1 => 2) => 3, ((1 => 2) => 3) => 4)sourceBase.foldr —Methodfoldr(op, itr; [init])Likereduce, but with guaranteed right associativity. If provided, the keyword argumentinit will be used exactly once. In general, it will be necessary to provideinit to work with empty collections.
Examples
julia> foldr(=>, 1:4)1 => (2 => (3 => 4))julia> foldr(=>, 1:4; init=0)1 => (2 => (3 => (4 => 0)))sourceBase.maximum —Functionmaximum(f, A::AbstractArray; dims)Compute the maximum value by calling the functionf on each element of an array over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> maximum(abs2, A, dims=1)1×2 Matrix{Int64}: 9 16julia> maximum(abs2, A, dims=2)2×1 Matrix{Int64}: 4 16sourcemaximum(A::AbstractArray; dims)Compute the maximum value of an array over the given dimensions. See also themax(a,b) function to take the maximum of two or more arguments, which can be applied elementwise to arrays viamax.(a,b).
See also:maximum!,extrema,findmax,argmax.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> maximum(A, dims=1)1×2 Matrix{Int64}: 3 4julia> maximum(A, dims=2)2×1 Matrix{Int64}: 2 4sourcemaximum(itr; [init])Return the largest element in a collection.
The value returned for emptyitr can be specified byinit. It must be a neutral element formax (i.e. which is less than or equal to any other element) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> maximum(-20.5:10)9.5julia> maximum([1,2,3])3julia> maximum(())ERROR: ArgumentError: reducing over an empty collection is not allowed; consider supplying `init` to the reducerStacktrace:[...]julia> maximum((); init=-Inf)-Infsourcemaximum(f, itr; [init])Return the largest result of calling functionf on each element ofitr.
The value returned for emptyitr can be specified byinit. It must be a neutral element formax (i.e. which is less than or equal to any other element) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> maximum(length, ["Julion", "Julia", "Jule"])6julia> maximum(length, []; init=-1)-1julia> maximum(sin, Real[]; init=-1.0) # good, since output of sin is >= -1-1.0sourceBase.maximum! —Functionmaximum!(r, A)Compute the maximum value ofA over the singleton dimensions ofr, and write results tor.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> maximum!([1; 1], A)2-element Vector{Int64}: 2 4julia> maximum!([1 1], A)1×2 Matrix{Int64}: 3 4sourceBase.minimum —Functionminimum(f, A::AbstractArray; dims)Compute the minimum value by calling the functionf on each element of an array over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> minimum(abs2, A, dims=1)1×2 Matrix{Int64}: 1 4julia> minimum(abs2, A, dims=2)2×1 Matrix{Int64}: 1 9sourceminimum(A::AbstractArray; dims)Compute the minimum value of an array over the given dimensions. See also themin(a,b) function to take the minimum of two or more arguments, which can be applied elementwise to arrays viamin.(a,b).
See also:minimum!,extrema,findmin,argmin.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> minimum(A, dims=1)1×2 Matrix{Int64}: 1 2julia> minimum(A, dims=2)2×1 Matrix{Int64}: 1 3sourceminimum(itr; [init])Return the smallest element in a collection.
The value returned for emptyitr can be specified byinit. It must be a neutral element formin (i.e. which is greater than or equal to any other element) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> minimum(-20.5:10)-20.5julia> minimum([1,2,3])1julia> minimum([])ERROR: ArgumentError: reducing over an empty collection is not allowed; consider supplying `init` to the reducerStacktrace:[...]julia> minimum([]; init=Inf)Infsourceminimum(f, itr; [init])Return the smallest result of calling functionf on each element ofitr.
The value returned for emptyitr can be specified byinit. It must be a neutral element formin (i.e. which is greater than or equal to any other element) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> minimum(length, ["Julion", "Julia", "Jule"])4julia> minimum(length, []; init=typemax(Int64))9223372036854775807julia> minimum(sin, Real[]; init=1.0) # good, since output of sin is <= 11.0sourceBase.minimum! —Functionminimum!(r, A)Compute the minimum value ofA over the singleton dimensions ofr, and write results tor.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> minimum!([1; 1], A)2-element Vector{Int64}: 1 3julia> minimum!([1 1], A)1×2 Matrix{Int64}: 1 2sourceBase.extrema —Functionextrema(f, A::AbstractArray; dims) -> Array{Tuple}Compute the minimum and maximum off applied to each element in the given dimensions ofA.
extrema(A::AbstractArray; dims) -> Array{Tuple}Compute the minimum and maximum elements of an array over the given dimensions.
See also:minimum,maximum,extrema!.
Examples
julia> A = reshape(Vector(1:2:16), (2,2,2))2×2×2 Array{Int64, 3}:[:, :, 1] = 1 5 3 7[:, :, 2] = 9 13 11 15julia> extrema(A, dims = (1,2))1×1×2 Array{Tuple{Int64, Int64}, 3}:[:, :, 1] = (1, 7)[:, :, 2] = (9, 15)sourceextrema(f, itr; [init]) -> (mn, mx)Compute both the minimummn and maximummx off applied to each element initr and return them as a 2-tuple. Only one pass is made overitr.
The value returned for emptyitr can be specified byinit. It must be a 2-tuple whose first and second elements are neutral elements formin andmax respectively (i.e. which are greater/less than or equal to any other element). It is used for non-empty collections. Note: it implies that, for emptyitr, the returned value(mn, mx) satisfiesmn ≥ mx even though for non-emptyitr it satisfiesmn ≤ mx. This is a "paradoxical" but yet expected result.
Examples
julia> extrema(sin, 0:π)(0.0, 0.9092974268256817)julia> extrema(sin, Real[]; init = (1.0, -1.0)) # good, since -1 ≤ sin(::Real) ≤ 1(1.0, -1.0)sourceextrema(itr; [init]) -> (mn, mx)Compute both the minimummn and maximummx element in a single pass, and return them as a 2-tuple.
The value returned for emptyitr can be specified byinit. It must be a 2-tuple whose first and second elements are neutral elements formin andmax respectively (i.e. which are greater/less than or equal to any other element). As a consequence, whenitr is empty the returned(mn, mx) tuple will satisfymn ≥ mx. Wheninit is specified it may be used even for non-emptyitr.
Examples
julia> extrema(2:10)(2, 10)julia> extrema([9,pi,4.5])(3.141592653589793, 9.0)julia> extrema([]; init = (Inf, -Inf))(Inf, -Inf)sourceBase.extrema! —Functionextrema!(r, A)Compute the minimum and maximum value ofA over the singleton dimensions ofr, and write results tor.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> extrema!([(1, 1); (1, 1)], A)2-element Vector{Tuple{Int64, Int64}}: (1, 2) (3, 4)julia> extrema!([(1, 1);; (1, 1)], A)1×2 Matrix{Tuple{Int64, Int64}}: (1, 3) (2, 4)sourceBase.argmax —Functionargmax(A; dims) -> indicesFor an array input, return the indices of the maximum elements over the given dimensions.NaN is treated as greater than all other values exceptmissing.
Examples
julia> A = [1.0 2; 3 4]2×2 Matrix{Float64}: 1.0 2.0 3.0 4.0julia> argmax(A, dims=1)1×2 Matrix{CartesianIndex{2}}: CartesianIndex(2, 1) CartesianIndex(2, 2)julia> argmax(A, dims=2)2×1 Matrix{CartesianIndex{2}}: CartesianIndex(1, 2) CartesianIndex(2, 2)sourceargmax(itr)Return the index or key of the maximal element in a collection. If there are multiple maximal elements, then the first one will be returned.
The collection must not be empty.
Indices are of the same type as those returned bykeys(itr) andpairs(itr).
Values are compared withisless.
Examples
julia> argmax([8, 0.1, -9, pi])1julia> argmax([1, 7, 7, 6])2julia> argmax([1, 7, 7, NaN])4sourceargmax(f, domain)Return a valuex fromdomain for whichf(x) is maximised. If there are multiple maximal values forf(x) then the first one will be found.
domain must be a non-empty iterable.
Values are compared withisless.
Examples
julia> argmax(abs, -10:5)-10julia> argmax(cos, 0:π/2:2π)0.0sourceargmax(r::AbstractRange)Ranges can have multiple maximal elements. In that caseargmax will return a maximal index, but not necessarily the first one.
Base.argmin —Functionargmin(A; dims) -> indicesFor an array input, return the indices of the minimum elements over the given dimensions.NaN is treated as less than all other values exceptmissing.
Examples
julia> A = [1.0 2; 3 4]2×2 Matrix{Float64}: 1.0 2.0 3.0 4.0julia> argmin(A, dims=1)1×2 Matrix{CartesianIndex{2}}: CartesianIndex(1, 1) CartesianIndex(1, 2)julia> argmin(A, dims=2)2×1 Matrix{CartesianIndex{2}}: CartesianIndex(1, 1) CartesianIndex(2, 1)sourceargmin(itr)Return the index or key of the minimal element in a collection. If there are multiple minimal elements, then the first one will be returned.
The collection must not be empty.
Indices are of the same type as those returned bykeys(itr) andpairs(itr).
NaN is treated as less than all other values exceptmissing.
Examples
julia> argmin([8, 0.1, -9, pi])3julia> argmin([7, 1, 1, 6])2julia> argmin([7, 1, 1, NaN])4sourceargmin(f, domain)Return a valuex fromdomain for whichf(x) is minimised. If there are multiple minimal values forf(x) then the first one will be found.
domain must be a non-empty iterable.
NaN is treated as less than all other values exceptmissing.
Examples
julia> argmin(sign, -10:5)-10julia> argmin(x -> -x^3 + x^2 - 10, -5:5)5julia> argmin(acos, 0:0.1:1)1.0sourceargmin(r::AbstractRange)Ranges can have multiple minimal elements. In that caseargmin will return a minimal index, but not necessarily the first one.
Base.findmax —Functionfindmax(f, A; dims) -> (f(x), index)For an array input, returns the value in the codomain and index of the corresponding value which maximizef over the given dimensions.
Examples
julia> A = [-1.0 1; -0.5 2]2×2 Matrix{Float64}: -1.0 1.0 -0.5 2.0julia> findmax(abs2, A, dims=1)([1.0 4.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(2, 2)])julia> findmax(abs2, A, dims=2)([1.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 2);;])sourcefindmax(A; dims) -> (maxval, index)For an array input, returns the value and index of the maximum over the given dimensions.NaN is treated as greater than all other values exceptmissing.
Examples
julia> A = [1.0 2; 3 4]2×2 Matrix{Float64}: 1.0 2.0 3.0 4.0julia> findmax(A, dims=1)([3.0 4.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(2, 2)])julia> findmax(A, dims=2)([2.0; 4.0;;], CartesianIndex{2}[CartesianIndex(1, 2); CartesianIndex(2, 2);;])sourcefindmax(itr) -> (x, index)Return the maximal element of the collectionitr and its index or key. If there are multiple maximal elements, then the first one will be returned. Values are compared withisless.
Indices are of the same type as those returned bykeys(itr) andpairs(itr).
See also:findmin,argmax,maximum.
Examples
julia> findmax([8, 0.1, -9, pi])(8.0, 1)julia> findmax([1, 7, 7, 6])(7, 2)julia> findmax([1, 7, 7, NaN])(NaN, 4)sourcefindmax(f, domain) -> (f(x), index)Return a pair of a value in the codomain (outputs off) and the index or key of the corresponding value in thedomain (inputs tof) such thatf(x) is maximised. If there are multiple maximal points, then the first one will be returned.
domain must be a non-empty iterable supportingkeys. Indices are of the same type as those returned bykeys(domain).
Values are compared withisless.
Examples
julia> findmax(identity, 5:9)(9, 5)julia> findmax(-, 1:10)(-1, 1)julia> findmax(first, [(1, :a), (3, :b), (3, :c)])(3, 2)julia> findmax(cos, 0:π/2:2π)(1.0, 1)sourceBase.findmin —Functionfindmin(f, A; dims) -> (f(x), index)For an array input, returns the value in the codomain and index of the corresponding value which minimizef over the given dimensions.
Examples
julia> A = [-1.0 1; -0.5 2]2×2 Matrix{Float64}: -1.0 1.0 -0.5 2.0julia> findmin(abs2, A, dims=1)([0.25 1.0], CartesianIndex{2}[CartesianIndex(2, 1) CartesianIndex(1, 2)])julia> findmin(abs2, A, dims=2)([1.0; 0.25;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])sourcefindmin(A; dims) -> (minval, index)For an array input, returns the value and index of the minimum over the given dimensions.NaN is treated as less than all other values exceptmissing.
Examples
julia> A = [1.0 2; 3 4]2×2 Matrix{Float64}: 1.0 2.0 3.0 4.0julia> findmin(A, dims=1)([1.0 2.0], CartesianIndex{2}[CartesianIndex(1, 1) CartesianIndex(1, 2)])julia> findmin(A, dims=2)([1.0; 3.0;;], CartesianIndex{2}[CartesianIndex(1, 1); CartesianIndex(2, 1);;])sourcefindmin(itr) -> (x, index)Return the minimal element of the collectionitr and its index or key. If there are multiple minimal elements, then the first one will be returned.NaN is treated as less than all other values exceptmissing.
Indices are of the same type as those returned bykeys(itr) andpairs(itr).
See also:findmax,argmin,minimum.
Examples
julia> findmin([8, 0.1, -9, pi])(-9.0, 3)julia> findmin([1, 7, 7, 6])(1, 1)julia> findmin([1, 7, 7, NaN])(NaN, 4)sourcefindmin(f, domain) -> (f(x), index)Return a pair of a value in the codomain (outputs off) and the index or key of the corresponding value in thedomain (inputs tof) such thatf(x) is minimised. If there are multiple minimal points, then the first one will be returned.
domain must be a non-empty iterable.
Indices are of the same type as those returned bykeys(domain) andpairs(domain).
NaN is treated as less than all other values exceptmissing.
Examples
julia> findmin(identity, 5:9)(5, 1)julia> findmin(-, 1:10)(-10, 10)julia> findmin(first, [(2, :a), (2, :b), (3, :c)])(2, 1)julia> findmin(cos, 0:π/2:2π)(-1.0, 3)sourceBase.findmax! —Functionfindmax!(rval, rind, A) -> (maxval, index)Find the maximum ofA and the corresponding linear index along singleton dimensions ofrval andrind, and store the results inrval andrind.NaN is treated as greater than all other values exceptmissing.
Base.findmin! —Functionfindmin!(rval, rind, A) -> (minval, index)Find the minimum ofA and the corresponding linear index along singleton dimensions ofrval andrind, and store the results inrval andrind.NaN is treated as less than all other values exceptmissing.
Base.sum —Functionsum(f, A::AbstractArray; dims)Sum the results of calling functionf on each element of an array over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> sum(abs2, A, dims=1)1×2 Matrix{Int64}: 10 20julia> sum(abs2, A, dims=2)2×1 Matrix{Int64}: 5 25sourcesum(A::AbstractArray; dims)Sum elements of an array over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> sum(A, dims=1)1×2 Matrix{Int64}: 4 6julia> sum(A, dims=2)2×1 Matrix{Int64}: 3 7sourcesum(itr; [init])Return the sum of all elements in a collection.
The return type isInt for signed integers of less than system word size, andUInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for emptyitr can be specified byinit. It must be the additive identity (i.e. zero) as it is unspecified whetherinit is used for non-empty collections.
See also:reduce,mapreduce,count,union.
Examples
julia> sum(1:20)210julia> sum(1:20; init = 0.0)210.0sourcesum(f, itr; [init])Sum the results of calling functionf on each element ofitr.
The return type isInt for signed integers of less than system word size, andUInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for emptyitr can be specified byinit. It must be the additive identity (i.e. zero) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> sum(abs2, [2; 3; 4])29Note the important difference betweensum(A) andreduce(+, A) for arrays with small integer eltype:
julia> sum(Int8[100, 28])128julia> reduce(+, Int8[100, 28])-128In the former case, the integers are widened to system word size and therefore the result is 128. In the latter case, no such widening happens and integer overflow results in -128.
sourceBase.prod —Functionprod(f, A::AbstractArray; dims)Multiply the results of calling the functionf on each element of an array over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> prod(abs2, A, dims=1)1×2 Matrix{Int64}: 9 64julia> prod(abs2, A, dims=2)2×1 Matrix{Int64}: 4 144sourceprod(A::AbstractArray; dims)Multiply elements of an array over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> prod(A, dims=1)1×2 Matrix{Int64}: 3 8julia> prod(A, dims=2)2×1 Matrix{Int64}: 2 12sourceprod(itr; [init])Return the product of all elements of a collection.
The return type isInt for signed integers of less than system word size, andUInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for emptyitr can be specified byinit. It must be the multiplicative identity (i.e. one) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> prod(1:5)120julia> prod(1:5; init = 1.0)120.0sourceprod(f, itr; [init])Return the product off applied to each element ofitr.
The return type isInt for signed integers of less than system word size, andUInt for unsigned integers of less than system word size. For all other arguments, a common return type is found to which all arguments are promoted.
The value returned for emptyitr can be specified byinit. It must be the multiplicative identity (i.e. one) as it is unspecified whetherinit is used for non-empty collections.
Examples
julia> prod(abs2, [2; 3; 4])576sourceBase.prod! —Functionprod!(r, A)Multiply elements ofA over the singleton dimensions ofr, and write results tor.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> prod!([1; 1], A)2-element Vector{Int64}: 2 12julia> prod!([1 1], A)1×2 Matrix{Int64}: 3 8sourceBase.any —Methodany(itr) -> BoolTest whether any elements of a boolean collection aretrue, returningtrue as soon as the firsttrue value initr is encountered (short-circuiting). To short-circuit onfalse, useall.
If the input containsmissing values, returnmissing if all non-missing values arefalse (or equivalently, if the input contains notrue value), followingthree-valued logic.
Examples
julia> a = [true,false,false,true]4-element Vector{Bool}: 1 0 0 1julia> any(a)truejulia> any((println(i); v) for (i, v) in enumerate(a))1truejulia> any([missing, true])truejulia> any([false, missing])missingsourceBase.any —Methodany(p, itr) -> BoolDetermine whether predicatep returnstrue for any elements ofitr, returningtrue as soon as the first item initr for whichp returnstrue is encountered (short-circuiting). To short-circuit onfalse, useall.
If the input containsmissing values, returnmissing if all non-missing values arefalse (or equivalently, if the input contains notrue value), followingthree-valued logic.
Examples
julia> any(i->(4<=i<=6), [3,5,7])truejulia> any(i -> (println(i); i > 3), 1:10)1234truejulia> any(i -> i > 0, [1, missing])truejulia> any(i -> i > 0, [-1, missing])missingjulia> any(i -> i > 0, [-1, 0])falsesourceBase.all —Methodall(itr) -> BoolTest whether all elements of a boolean collection aretrue, returningfalse as soon as the firstfalse value initr is encountered (short-circuiting). To short-circuit ontrue, useany.
If the input containsmissing values, returnmissing if all non-missing values aretrue (or equivalently, if the input contains nofalse value), followingthree-valued logic.
See also:all!,any,count,&,&&,allunique.
Examples
julia> a = [true,false,false,true]4-element Vector{Bool}: 1 0 0 1julia> all(a)falsejulia> all((println(i); v) for (i, v) in enumerate(a))12falsejulia> all([missing, false])falsejulia> all([true, missing])missingsourceBase.all —Methodall(p, itr) -> BoolDetermine whether predicatep returnstrue for all elements ofitr, returningfalse as soon as the first item initr for whichp returnsfalse is encountered (short-circuiting). To short-circuit ontrue, useany.
If the input containsmissing values, returnmissing if all non-missing values aretrue (or equivalently, if the input contains nofalse value), followingthree-valued logic.
Examples
julia> all(i->(4<=i<=6), [4,5,6])truejulia> all(i -> (println(i); i < 3), 1:10)123falsejulia> all(i -> i > 0, [1, missing])missingjulia> all(i -> i > 0, [-1, missing])falsejulia> all(i -> i > 0, [1, 2])truesourceBase.count —Functioncount([f=identity,] A::AbstractArray; dims=:)Count the number of elements inA for whichf returnstrue over the given dimensions.
Examples
julia> A = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> count(<=(2), A, dims=1)1×2 Matrix{Int64}: 1 1julia> count(<=(2), A, dims=2)2×1 Matrix{Int64}: 2 0sourcecount( pattern::Union{AbstractChar,AbstractString,AbstractPattern}, string::AbstractString; overlap::Bool = false,)Return the number of matches forpattern instring. This is equivalent to callinglength(findall(pattern, string)) but more efficient.
Ifoverlap=true, the matching sequences are allowed to overlap indices in the original string, otherwise they must be from disjoint character ranges.
Examples
julia> count('a', "JuliaLang")2julia> count(r"a(.)a", "cabacabac", overlap=true)3julia> count(r"a(.)a", "cabacabac")2sourcecount([f=identity,] itr; init=0) -> IntegerCount the number of elements initr for which the functionf returnstrue. Iff is omitted, count the number oftrue elements initr (which should be a collection of boolean values).init optionally specifies the value to start counting from and therefore also determines the output type.
Examples
julia> count(i->(4<=i<=6), [2,3,4,5,6])3julia> count([true, false, true, true])3julia> count(>(3), 1:7, init=0x03)0x07sourceBase.foreach —Functionforeach(f, c...) -> NothingCall functionf on each element of iterablec. For multiple iterable arguments,f is called elementwise, and iteration stops when any iterator is finished.
foreach should be used instead ofmap when the results off are not needed, for example inforeach(println, array).
Examples
julia> tri = 1:3:7; res = Int[];julia> foreach(x -> push!(res, x^2), tri)julia> res3-element Vector{Int64}: 1 16 49julia> foreach((x, y) -> println(x, " with ", y), tri, 'a':'z')1 with a4 with b7 with csourceBase.map —Functionmap(f, A::AbstractArray...) -> N-arrayWhen acting on multi-dimensional arrays of the samendims, they must all have the sameaxes, and the answer will too.
See alsobroadcast, which allows mismatched sizes.
Examples
julia> map(//, [1 2; 3 4], [4 3; 2 1])2×2 Matrix{Rational{Int64}}: 1//4 2//3 3//2 4//1julia> map(+, [1 2; 3 4], zeros(2,1))ERROR: DimensionMismatchjulia> map(+, [1 2; 3 4], [1,10,100,1000], zeros(3,1)) # iterates until 3rd is exhausted3-element Vector{Float64}: 2.0 13.0 102.0sourcemap(f, c...) -> collectionTransform collectionc by applyingf to each element. For multiple collection arguments, applyf elementwise, and stop when any of them is exhausted.
The element type of the result is determined in the same manner as incollect.
See alsomap!,foreach,mapreduce,mapslices,zip,Iterators.map.
Examples
julia> map(x -> x * 2, [1, 2, 3])3-element Vector{Int64}: 2 4 6julia> map(+, [1, 2, 3], [10, 20, 30, 400, 5000])3-element Vector{Int64}: 11 22 33sourceBase.map! —Functionmap!(f, values(dict::AbstractDict))Modifiesdict by transforming each value fromval tof(val). Note that the type ofdict cannot be changed: iff(val) is not an instance of the value type ofdict then it will be converted to the value type if possible and otherwise raise an error.
Examples
julia> d = Dict(:a => 1, :b => 2)Dict{Symbol, Int64} with 2 entries: :a => 1 :b => 2julia> map!(v -> v-1, values(d))ValueIterator for a Dict{Symbol, Int64} with 2 entries. Values: 0 1sourcemap!(function, array)Likemap, but stores the result in the same array.
This method requires Julia 1.12 or later. To support previous versions too, use the equivalentmap!(function, array, array).
Examples
julia> a = [1 2 3; 4 5 6];julia> map!(x -> x^3, a);julia> a2×3 Matrix{Int64}: 1 8 27 64 125 216sourcemap!(function, destination, collection...)Likemap, but stores the result indestination rather than a new collection.destination must be at least as large as the smallest collection.
See also:map,foreach,zip,copyto!.
Examples
julia> a = zeros(3);julia> map!(x -> x * 2, a, [1, 2, 3]);julia> a3-element Vector{Float64}: 2.0 4.0 6.0julia> map!(+, zeros(Int, 5), 100:999, 1:3)5-element Vector{Int64}: 101 103 105 0 0sourceBase.mapreduce —Methodmapreduce(f, op, itrs...; [init])Apply functionf to each element(s) initrs, and then reduce the result using the binary functionop. If provided,init must be a neutral element forop that will be returned for empty collections. It is unspecified whetherinit is used for non-empty collections. In general, it will be necessary to provideinit to work with empty collections.
mapreduce is functionally equivalent to callingreduce(op, map(f, itr); init=init), but will in general execute faster since no intermediate collection needs to be created. See documentation forreduce andmap.
Examples
julia> mapreduce(x->x^2, +, [1:3;]) # == 1 + 4 + 914The associativity of the reduction is implementation-dependent. Additionally, some implementations may reuse the return value off for elements that appear multiple times initr. Usemapfoldl ormapfoldr instead for guaranteed left or right associativity and invocation off for every value.
Base.mapfoldl —MethodBase.mapfoldr —MethodBase.first —Functionfirst(s::AbstractString, n::Integer)Get a string consisting of the firstn characters ofs.
Examples
julia> first("∀ϵ≠0: ϵ²>0", 0)""julia> first("∀ϵ≠0: ϵ²>0", 1)"∀"julia> first("∀ϵ≠0: ϵ²>0", 3)"∀ϵ≠"sourcefirst(itr, n::Integer)Get the firstn elements of the iterable collectionitr, or fewer elements ifitr is not long enough.
See also:startswith,Iterators.take.
Examples
julia> first(["foo", "bar", "qux"], 2)2-element Vector{String}: "foo" "bar"julia> first(1:6, 10)1:6julia> first(Bool[], 1)Bool[]sourcefirst(coll)Get the first element of an iterable collection. Return the start point of anAbstractRange even if it is empty.
See also:only,firstindex,last.
Examples
julia> first(2:2:10)2julia> first([1; 2; 3; 4])1sourceBase.last —Functionlast(s::AbstractString, n::Integer)Get a string consisting of the lastn characters ofs.
Examples
julia> last("∀ϵ≠0: ϵ²>0", 0)""julia> last("∀ϵ≠0: ϵ²>0", 1)"0"julia> last("∀ϵ≠0: ϵ²>0", 3)"²>0"sourcelast(itr, n::Integer)Get the lastn elements of the iterable collectionitr, or fewer elements ifitr is not long enough.
Examples
julia> last(["foo", "bar", "qux"], 2)2-element Vector{String}: "bar" "qux"julia> last(1:6, 10)1:6julia> last(Float64[], 1)Float64[]sourcelast(coll)Get the last element of an ordered collection, if it can be computed in O(1) time. This is accomplished by callinglastindex to get the last index. Return the end point of anAbstractRange even if it is empty.
Examples
julia> last(1:2:10)9julia> last([1; 2; 3; 4])4sourceBase.front —FunctionBase.step —Functionstep(r)Get the step size of anAbstractRange object.
Examples
julia> step(1:10)1julia> step(1:2:10)2julia> step(2.5:0.3:10.9)0.3julia> step(range(2.5, stop=10.9, length=85))0.1sourceBase.collect —Methodcollect(iterator)Return anArray of all items in a collection or iterator. For dictionaries, returns aVector ofkey=>valuePairs. If the argument is array-like or is an iterator with theHasShape trait, the result will have the same shape and number of dimensions as the argument.
Used bycomprehensions to turn agenerator expression into anArray. Thus,on generators, the square-brackets notation may be used instead of callingcollect, see second example.
The element type of the returned array is based on the types of the values collected. However, if the iterator is empty then the element type of the returned (empty) array is determined by type inference.
Examples
Collect items from aUnitRange{Int64} collection:
julia> collect(1:3)3-element Vector{Int64}: 1 2 3Collect items from a generator (same output as[x^2 for x in 1:3]):
julia> collect(x^2 for x in 1:3)3-element Vector{Int64}: 1 4 9Collecting an empty iterator where the result type depends on type inference:
julia> [rand(Bool) ? 1 : missing for _ in []]Union{Missing, Int64}[]When the iterator is non-empty, the result type depends only on values:
julia> [rand(Bool) ? 1 : missing for _ in [""]]1-element Vector{Int64}: 1sourceBase.collect —Methodcollect(element_type, collection)Return anArray with the given element type of all items in a collection or iterable. The result has the same shape and number of dimensions ascollection.
Examples
julia> collect(Float64, 1:2:5)3-element Vector{Float64}: 1.0 3.0 5.0sourceBase.filter —Functionfilter(f, itr::SkipMissing{<:AbstractArray})Return a vector similar to the array wrapped by the givenSkipMissing iterator but with all missing elements and those for whichf returnsfalse removed.
Examples
julia> x = [1 2; missing 4]2×2 Matrix{Union{Missing, Int64}}: 1 2 missing 4julia> filter(isodd, skipmissing(x))1-element Vector{Int64}: 1sourcefilter(f, d::AbstractDict)Return a copy ofd, removing elements for whichf isfalse. The functionf is passedkey=>value pairs.
Examples
julia> d = Dict(1=>"a", 2=>"b")Dict{Int64, String} with 2 entries: 2 => "b" 1 => "a"julia> filter(p->isodd(p.first), d)Dict{Int64, String} with 1 entry: 1 => "a"sourcefilter(f)Create a function that filters its arguments with functionf usingfilter, i.e. a function equivalent tox -> filter(f, x).
The returned function is of typeBase.Fix1{typeof(filter)}, which can be used to implement specialized methods.
Examples
julia> (1, 2, Inf, 4, NaN, 6) |> filter(isfinite)(1, 2, 4, 6)julia> map(filter(iseven), [1:3, 2:4, 3:5])3-element Vector{Vector{Int64}}: [2] [2, 4] [4]sourcefilter(f, a)Return a copy of collectiona, removing elements for whichf isfalse. The functionf is passed one argument.
See also:filter!,Iterators.filter.
Examples
julia> a = 1:101:10julia> filter(isodd, a)5-element Vector{Int64}: 1 3 5 7 9sourceBase.filter! —Functionfilter!(f, d::AbstractDict)Updated, removing elements for whichf isfalse. The functionf is passedkey=>value pairs.
Examples
julia> d = Dict(1=>"a", 2=>"b", 3=>"c")Dict{Int64, String} with 3 entries: 2 => "b" 3 => "c" 1 => "a"julia> filter!(p->isodd(p.first), d)Dict{Int64, String} with 2 entries: 3 => "c" 1 => "a"sourcefilter!(f, a)Update collectiona, removing elements for whichf isfalse. The functionf is passed one argument.
Examples
julia> filter!(isodd, Vector(1:10))5-element Vector{Int64}: 1 3 5 7 9sourceBase.replace —Methodreplace(A, old_new::Pair...; [count::Integer])Return a copy of collectionA where, for each pairold=>new inold_new, all occurrences ofold are replaced bynew. Equality is determined usingisequal. Ifcount is specified, then replace at mostcount occurrences in total.
The element type of the result is chosen using promotion (seepromote_type) based on the element type ofA and on the types of thenew values in pairs. Ifcount is omitted and the element type ofA is aUnion, the element type of the result will not include singleton types which are replaced with values of a different type: for example,Union{T,Missing} will becomeT ifmissing is replaced.
See alsoreplace!,splice!,delete!,insert!.
Examples
julia> replace([1, 2, 1, 3], 1=>0, 2=>4, count=2)4-element Vector{Int64}: 0 4 1 3julia> replace([1, missing], missing=>0)2-element Vector{Int64}: 1 0sourceBase.replace —Methodreplace(new::Union{Function, Type}, A; [count::Integer])Return a copy ofA where each valuex inA is replaced bynew(x). Ifcount is specified, then replace at mostcount values in total (replacements being defined asnew(x) !== x).
Examples
julia> replace(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])4-element Vector{Int64}: 2 2 6 4julia> replace(Dict(1=>2, 3=>4)) do kv first(kv) < 3 ? first(kv)=>3 : kv endDict{Int64, Int64} with 2 entries: 3 => 4 1 => 3sourceBase.replace! —Functionreplace!(new::Union{Function, Type}, A; [count::Integer])Replace each elementx in collectionA bynew(x). Ifcount is specified, then replace at mostcount values in total (replacements being defined asnew(x) !== x).
Examples
julia> replace!(x -> isodd(x) ? 2x : x, [1, 2, 3, 4])4-element Vector{Int64}: 2 2 6 4julia> replace!(Dict(1=>2, 3=>4)) do kv first(kv) < 3 ? first(kv)=>3 : kv endDict{Int64, Int64} with 2 entries: 3 => 4 1 => 3julia> replace!(x->2x, Set([3, 6]))Set{Int64} with 2 elements: 6 12sourcereplace!(A, old_new::Pair...; [count::Integer])For each pairold=>new inold_new, replace all occurrences ofold in collectionA bynew. Equality is determined usingisequal. Ifcount is specified, then replace at mostcount occurrences in total. See alsoreplace.
Examples
julia> replace!([1, 2, 1, 3], 1=>0, 2=>4, count=2)4-element Vector{Int64}: 0 4 1 3julia> replace!(Set([1, 2, 3]), 1=>0)Set{Int64} with 3 elements: 0 2 3sourceBase.rest —FunctionBase.rest(collection[, itr_state])Generic function for taking the tail ofcollection, starting from a specific iteration stateitr_state. Return aTuple, ifcollection itself is aTuple, a subtype ofAbstractVector, ifcollection is anAbstractArray, a subtype ofAbstractString ifcollection is anAbstractString, and an arbitrary iterator, falling back toIterators.rest(collection[, itr_state]), otherwise.
Can be overloaded for user-defined collection types to customize the behavior ofslurping in assignments in final position, likea, b... = collection.
See also:first,Iterators.rest,Base.split_rest.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> first, state = iterate(a)(1, 2)julia> first, Base.rest(a, state)(1, [3, 2, 4])sourceBase.split_rest —FunctionBase.split_rest(collection, n::Int[, itr_state]) -> (rest_but_n, last_n)Generic function for splitting the tail ofcollection, starting from a specific iteration stateitr_state. Returns a tuple of two new collections. The first one contains all elements of the tail but then last ones, which make up the second collection.
The type of the first collection generally follows that ofBase.rest, except that the fallback case is not lazy, but is collected eagerly into a vector.
Can be overloaded for user-defined collection types to customize the behavior ofslurping in assignments in non-final position, likea, b..., c = collection.
See also:Base.rest.
Examples
julia> a = [1 2; 3 4]2×2 Matrix{Int64}: 1 2 3 4julia> first, state = iterate(a)(1, 2)julia> first, Base.split_rest(a, 1, state)(1, ([3, 2], [4]))sourceBase.getindex —Functiongetindex(collection, key...)Retrieve the value(s) stored at the given key or index within a collection. The syntaxa[i,j,...] is converted by the compiler togetindex(a, i, j, ...).
Examples
julia> A = Dict("a" => 1, "b" => 2)Dict{String, Int64} with 2 entries: "b" => 2 "a" => 1julia> getindex(A, "a")1sourceBase.setindex! —Functionsetindex!(collection, value, key...)Store the given value at the given key or index within a collection. The syntaxa[i,j,...] = x is converted by the compiler to(setindex!(a, x, i, j, ...); x).
Examples
julia> a = Dict("a"=>1)Dict{String, Int64} with 1 entry: "a" => 1julia> setindex!(a, 2, "b")Dict{String, Int64} with 2 entries: "b" => 2 "a" => 1sourceBase.firstindex —Functionfirstindex(collection) -> Integerfirstindex(collection, d) -> IntegerReturn the first index ofcollection. Ifd is given, return the first index ofcollection along dimensiond.
The syntaxesA[begin] andA[1, begin] lower toA[firstindex(A)] andA[1, firstindex(A, 2)], respectively.
See also:first,axes,lastindex,nextind.
Examples
julia> firstindex([1,2,4])1julia> firstindex(rand(3,4,5), 2)1sourceBase.lastindex —Functionlastindex(collection) -> Integerlastindex(collection, d) -> IntegerReturn the last index ofcollection. Ifd is given, return the last index ofcollection along dimensiond.
The syntaxesA[end] andA[end, end] lower toA[lastindex(A)] andA[lastindex(A, 1), lastindex(A, 2)], respectively.
See also:axes,firstindex,eachindex,prevind.
Examples
julia> lastindex([1,2,4])3julia> lastindex(rand(3,4,5), 2)4sourceFully implemented by:
ArrayBitArrayAbstractArraySubArrayPartially implemented by:
Dict is the standard dictionary. Its implementation useshash as the hashing function for the key, andisequal to determine equality. Define these two functions for custom types to override how they are stored in a hash table.
IdDict is a special hash table where the keys are always object identities.
WeakKeyDict is a hash table implementation where the keys are weak references to objects, and thus may be garbage collected even when referenced in a hash table. LikeDict it useshash for hashing andisequal for equality, unlikeDict it does not convert keys on insertion.
Dicts can be created by passing pair objects constructed with=> to aDict constructor:Dict("A"=>1, "B"=>2). This call will attempt to infer type information from the keys and values (i.e. this example creates aDict{String, Int64}). To explicitly specify types use the syntaxDict{KeyType,ValueType}(...). For example,Dict{String,Int32}("A"=>1, "B"=>2).
Dictionaries may also be created with generators. For example,Dict(i => f(i) for i = 1:10).
Given a dictionaryD, the syntaxD[x] returns the value of keyx (if it exists) or throws an error, andD[x] = y stores the key-value pairx => y inD (replacing any existing value for the keyx). Multiple arguments toD[...] are converted to tuples; for example, the syntaxD[x,y] is equivalent toD[(x,y)], i.e. it refers to the value keyed by the tuple(x,y).
Base.AbstractDict —TypeBase.Dict —TypeDict([itr])Dict{K,V}() constructs a hash table with keys of typeK and values of typeV. Keys are compared withisequal and hashed withhash.
Given a single iterable argument, constructs aDict whose key-value pairs are taken from 2-tuples(key,value) generated by the argument.
Examples
julia> Dict([("A", 1), ("B", 2)])Dict{String, Int64} with 2 entries: "B" => 2 "A" => 1Alternatively, a sequence of pair arguments may be passed.
julia> Dict("A"=>1, "B"=>2)Dict{String, Int64} with 2 entries: "B" => 2 "A" => 1Keys are allowed to be mutable, but if you do mutate stored keys, the hash table may become internally inconsistent, in which case theDict will not work properly.IdDict can be an alternative if you need to mutate keys.
Base.IdDict —TypeIdDict([itr])IdDict{K,V}() constructs a hash table usingobjectid as hash and=== as equality with keys of typeK and values of typeV. SeeDict for further help andIdSet for the set version of this.
In the example below, theDict keys are allisequal and therefore get hashed the same, so they get overwritten. TheIdDict hashes by object-id, and thus preserves the 3 different keys.
Examples
julia> Dict(true => "yes", 1 => "no", 1.0 => "maybe")Dict{Real, String} with 1 entry: 1.0 => "maybe"julia> IdDict(true => "yes", 1 => "no", 1.0 => "maybe")IdDict{Any, String} with 3 entries: true => "yes" 1.0 => "maybe" 1 => "no"sourceBase.WeakKeyDict —TypeWeakKeyDict([itr])WeakKeyDict() constructs a hash table where the keys are weak references to objects which may be garbage collected even when referenced in a hash table.
SeeDict for further help. Note, unlikeDict,WeakKeyDict does not convert keys on insertion, as this would imply the key object was unreferenced anywhere before insertion.
See alsoWeakRef.
Base.ImmutableDict —TypeImmutableDictImmutableDict is a dictionary implemented as an immutable linked list, which is optimal for small dictionaries that are constructed over many individual insertions. Note that it is not possible to remove a value, although it can be partially overridden and hidden by inserting a new value with the same key.
ImmutableDict(KV::Pair)Create a new entry in theImmutableDict for akey => value pair
(key => value) in dict to see if this particular combination is in the properties setget(dict, key, default) to retrieve the most recent value for a particular keyBase.PersistentDict —TypePersistentDictPersistentDict is a dictionary implemented as an hash array mapped trie, which is optimal for situations where you need persistence, each operation returns a new dictionary separate from the previous one, but the underlying implementation is space-efficient and may share storage across multiple separate dictionaries.
PersistentDict(KV::Pair)Examples
julia> dict = Base.PersistentDict(:a=>1)Base.PersistentDict{Symbol, Int64} with 1 entry: :a => 1julia> dict2 = Base.delete(dict, :a)Base.PersistentDict{Symbol, Int64}()julia> dict3 = Base.PersistentDict(dict, :a=>2)Base.PersistentDict{Symbol, Int64} with 1 entry: :a => 2sourceBase.haskey —Functionhaskey(collection, key) -> BoolDetermine whether a collection has a mapping for a givenkey.
Examples
julia> D = Dict('a'=>2, 'b'=>3)Dict{Char, Int64} with 2 entries: 'a' => 2 'b' => 3julia> haskey(D, 'a')truejulia> haskey(D, 'c')falsesourceBase.get —Functionget(f::Union{Function, Type}, collection, key)Return the value stored for the given key, or if no mapping for the key is present, returnf(). Useget! to also store the default value in the dictionary.
This is intended to be called usingdo block syntax
get(dict, key) do # default value calculated here time()endsourceget(collection, key, default)Return the value stored for the given key, or the given default value if no mapping for the key is present.
Examples
julia> d = Dict("a"=>1, "b"=>2);julia> get(d, "a", 3)1julia> get(d, "c", 3)3sourceBase.get! —Functionget!(f::Union{Function, Type}, collection, key)Return the value stored for the given key, or if no mapping for the key is present, storekey => f(), and returnf().
This is intended to be called usingdo block syntax.
Examples
julia> squares = Dict{Int, Int}();julia> function get_square!(d, i) get!(d, i) do i^2 end endget_square! (generic function with 1 method)julia> get_square!(squares, 2)4julia> squaresDict{Int64, Int64} with 1 entry: 2 => 4sourceget!(collection, key, default)Return the value stored for the given key, or if no mapping for the key is present, storekey => default, and returndefault.
Examples
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);julia> get!(d, "a", 5)1julia> get!(d, "d", 4)4julia> dDict{String, Int64} with 4 entries: "c" => 3 "b" => 2 "a" => 1 "d" => 4sourceBase.getkey —Functiongetkey(collection, key, default)Return the key matching argumentkey if one exists incollection, otherwise returndefault.
Examples
julia> D = Dict('a'=>2, 'b'=>3)Dict{Char, Int64} with 2 entries: 'a' => 2 'b' => 3julia> getkey(D, 'a', 1)'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)julia> getkey(D, 'd', 'a')'a': ASCII/Unicode U+0061 (category Ll: Letter, lowercase)sourceBase.delete! —Functiondelete!(collection, key)Delete the mapping for the given key in a collection, if any, and return the collection.
Examples
julia> d = Dict("a"=>1, "b"=>2)Dict{String, Int64} with 2 entries: "b" => 2 "a" => 1julia> delete!(d, "b")Dict{String, Int64} with 1 entry: "a" => 1julia> delete!(d, "b") # d is left unchangedDict{String, Int64} with 1 entry: "a" => 1sourceBase.pop! —Methodpop!(collection, key[, default])Delete and return the mapping forkey if it exists incollection, otherwise returndefault, or throw an error ifdefault is not specified.
Examples
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);julia> pop!(d, "a")1julia> pop!(d, "d")ERROR: KeyError: key "d" not foundStacktrace:[...]julia> pop!(d, "e", 4)4sourceBase.values —Functionvalues(a::AbstractDict)Return an iterator over all values in a collection.collect(values(a)) returns an array of values. When the values are stored internally in a hash table, as is the case forDict, the order in which they are returned may vary. Butkeys(a),values(a) andpairs(a) all iteratea and return the elements in the same order.
Examples
julia> D = Dict('a'=>2, 'b'=>3)Dict{Char, Int64} with 2 entries: 'a' => 2 'b' => 3julia> collect(values(D))2-element Vector{Int64}: 2 3sourcevalues(iterator)For an iterator or collection that has keys and values, return an iterator over the values. This function simply returns its argument by default, since the elements of a general iterator are normally considered its "values".
Examples
julia> d = Dict("a"=>1, "b"=>2);julia> values(d)ValueIterator for a Dict{String, Int64} with 2 entries. Values: 2 1julia> values([2])1-element Vector{Int64}: 2sourceBase.pairs —Functionpairs(IndexLinear(), A)pairs(IndexCartesian(), A)pairs(IndexStyle(A), A)An iterator that accesses each element of the arrayA, returningi => x, wherei is the index for the element andx = A[i]. Identical topairs(A), except that the style of index can be selected. Also similar toenumerate(A), excepti will be a valid index forA, whileenumerate always counts from 1 regardless of the indices ofA.
SpecifyingIndexLinear() ensures thati will be an integer; specifyingIndexCartesian() ensures thati will be aBase.CartesianIndex; specifyingIndexStyle(A) chooses whichever has been defined as the native indexing style for arrayA.
Mutation of the bounds of the underlying array will invalidate this iterator.
Examples
julia> A = ["a" "d"; "b" "e"; "c" "f"];julia> for (index, value) in pairs(IndexStyle(A), A) println("$index $value") end1 a2 b3 c4 d5 e6 fjulia> S = view(A, 1:2, :);julia> for (index, value) in pairs(IndexStyle(S), S) println("$index $value") endCartesianIndex(1, 1) aCartesianIndex(2, 1) bCartesianIndex(1, 2) dCartesianIndex(2, 2) eSee alsoIndexStyle,axes.
pairs(collection)Return an iterator overkey => value pairs for any collection that maps a set of keys to a set of values. This includes arrays, where the keys are the array indices. When the entries are stored internally in a hash table, as is the case forDict, the order in which they are returned may vary. Butkeys(a),values(a) andpairs(a) all iteratea and return the elements in the same order.
Examples
julia> a = Dict(zip(["a", "b", "c"], [1, 2, 3]))Dict{String, Int64} with 3 entries: "c" => 3 "b" => 2 "a" => 1julia> pairs(a)Dict{String, Int64} with 3 entries: "c" => 3 "b" => 2 "a" => 1julia> foreach(println, pairs(["a", "b", "c"]))1 => "a"2 => "b"3 => "c"julia> (;a=1, b=2, c=3) |> pairs |> collect3-element Vector{Pair{Symbol, Int64}}: :a => 1 :b => 2 :c => 3julia> (;a=1, b=2, c=3) |> collect3-element Vector{Int64}: 1 2 3sourceBase.merge —Functionmerge(initial::StyledStrings.Face, others::StyledStrings.Face...)Merge the properties of theinitial face andothers, with later faces taking priority.
This is used to combine the styles of multiple faces, and to resolve inheritance.
merge(a::NamedTuple, iterable)Interpret an iterable of key-value pairs as a named tuple, and perform a merge.
julia> merge((a=1, b=2, c=3), [:b=>4, :d=>5])(a = 1, b = 4, c = 3, d = 5)sourcemerge(a::NamedTuple, bs::NamedTuple...)Construct a new named tuple by merging two or more existing ones, in a left-associative manner. Merging proceeds left-to-right, between pairs of named tuples, and so the order of fields present in both the leftmost and rightmost named tuples take the same position as they are found in the leftmost named tuple. However, values are taken from matching fields in the rightmost named tuple that contains that field. Fields present in only the rightmost named tuple of a pair are appended at the end. A fallback is implemented for when only a single named tuple is supplied, with signaturemerge(a::NamedTuple).
Examples
julia> merge((a=1, b=2, c=3), (b=4, d=5))(a = 1, b = 4, c = 3, d = 5)julia> merge((a=1, b=2), (b=3, c=(d=1,)), (c=(d=2,),))(a = 1, b = 3, c = (d = 2,))sourcemerge(d::AbstractDict, others::AbstractDict...)Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed. See alsomergewith for custom handling of values with the same key.
Examples
julia> a = Dict("foo" => 0.0, "bar" => 42.0)Dict{String, Float64} with 2 entries: "bar" => 42.0 "foo" => 0.0julia> b = Dict("baz" => 17, "bar" => 4711)Dict{String, Int64} with 2 entries: "bar" => 4711 "baz" => 17julia> merge(a, b)Dict{String, Float64} with 3 entries: "bar" => 4711.0 "baz" => 17.0 "foo" => 0.0julia> merge(b, a)Dict{String, Float64} with 3 entries: "bar" => 42.0 "baz" => 17.0 "foo" => 0.0sourceBase.mergewith —Functionmergewith(combine, d::AbstractDict, others::AbstractDict...)mergewith(combine)merge(combine, d::AbstractDict, others::AbstractDict...)Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. Values with the same key will be combined using the combiner function. The curried formmergewith(combine) returns the function(args...) -> mergewith(combine, args...).
Methodmerge(combine::Union{Function,Type}, args...) as an alias ofmergewith(combine, args...) is still available for backward compatibility.
Examples
julia> a = Dict("foo" => 0.0, "bar" => 42.0)Dict{String, Float64} with 2 entries: "bar" => 42.0 "foo" => 0.0julia> b = Dict("baz" => 17, "bar" => 4711)Dict{String, Int64} with 2 entries: "bar" => 4711 "baz" => 17julia> mergewith(+, a, b)Dict{String, Float64} with 3 entries: "bar" => 4753.0 "baz" => 17.0 "foo" => 0.0julia> ans == mergewith(+)(a, b)truejulia> mergewith(-, Dict(), Dict(:a=>1)) # Combining function only used if key is present in bothDict{Any, Any} with 1 entry: :a => 1sourceBase.merge! —FunctionBase.mergewith! —Functionmergewith!(combine, d::AbstractDict, others::AbstractDict...) -> dmergewith!(combine)merge!(combine, d::AbstractDict, others::AbstractDict...) -> dUpdate collection with pairs from the other collections. Values with the same key will be combined using the combiner function. The curried formmergewith!(combine) returns the function(args...) -> mergewith!(combine, args...).
Methodmerge!(combine::Union{Function,Type}, args...) as an alias ofmergewith!(combine, args...) is still available for backward compatibility.
Examples
julia> d1 = Dict(1 => 2, 3 => 4);julia> d2 = Dict(1 => 4, 4 => 5);julia> mergewith!(+, d1, d2);julia> d1Dict{Int64, Int64} with 3 entries: 4 => 5 3 => 4 1 => 6julia> mergewith!(-, d1, d1);julia> d1Dict{Int64, Int64} with 3 entries: 4 => 0 3 => 0 1 => 0julia> foldl(mergewith!(+), [d1, d2]; init=Dict{Int64, Int64}())Dict{Int64, Int64} with 3 entries: 4 => 5 3 => 0 1 => 4sourceBase.sizehint! —Functionsizehint!(s, n; first::Bool=false, shrink::Bool=true) -> sSuggest that collections reserve capacity for at leastn elements. That is, if you expect that you're going to have to push a lot of values ontos, you can avoid the cost of incremental reallocation by doing it once up front; this can improve performance.
Iffirst istrue, then any additional space is reserved before the start of the collection. This way, subsequent calls topushfirst! (instead ofpush!) may become faster. Supplying this keyword may result in an error if the collection is not ordered or ifpushfirst! is not supported for this collection.
Ifshrink=true (the default), the collection's capacity may be reduced if its current capacity is greater thann.
See alsoresize!.
Notes on the performance model
For types that supportsizehint!,
push! andappend! methods generally may (but are not required to) preallocate extra storage. For types implemented inBase, they typically do, using a heuristic optimized for a general use case.
sizehint! may control this preallocation. Again, it typically does this for types inBase.
empty! is nearly costless (and O(1)) for types that support this kind of preallocation.
Base.keytype —Functionkeytype(type)Get the key type of a dictionary type. Behaves similarly toeltype.
Examples
julia> keytype(Dict(Int32(1) => "foo"))Int32sourcekeytype(T::Type{<:AbstractArray})keytype(A::AbstractArray)Return the key type of an array. This is equal to theeltype of the result ofkeys(...), and is provided mainly for compatibility with the dictionary interface.
Examples
julia> keytype([1, 2, 3]) == Inttruejulia> keytype([1 2; 3 4])CartesianIndex{2}sourceBase.valtype —Functionvaltype(type)Get the value type of a dictionary type. Behaves similarly toeltype.
Examples
julia> valtype(Dict(Int32(1) => "foo"))StringsourceFully implemented by:
Partially implemented by:
Base.AbstractSet —TypeBase.Set —TypeSet{T} <: AbstractSet{T}Sets are mutable containers that provide fast membership testing.
Sets have efficient implementations of set operations such asin,union andintersect. Elements in aSet are unique, as determined by the elements' definition ofisequal. The order of elements in aSet is an implementation detail and cannot be relied on.
See also:AbstractSet,BitSet,Dict,push!,empty!,union!,in,isequal
Examples
julia> s = Set("aaBca")Set{Char} with 3 elements: 'a' 'c' 'B'julia> push!(s, 'b')Set{Char} with 4 elements: 'a' 'b' 'B' 'c'julia> s = Set([NaN, 0.0, 1.0, 2.0]);julia> -0.0 in s # isequal(0.0, -0.0) is falsefalsejulia> NaN in s # isequal(NaN, NaN) is truetruesourceBase.BitSet —TypeBase.IdSet —TypeIdSet{T}([itr])IdSet()IdSet{T}() constructs a set (seeSet) using=== as equality with values of typeT.
In the example below, the values are allisequal so they get overwritten in the ordinarySet. TheIdSet compares by=== and so preserves the 3 different values.
Examples
julia> Set(Any[true, 1, 1.0])Set{Any} with 1 element: 1.0julia> IdSet{Any}(Any[true, 1, 1.0])IdSet{Any} with 3 elements: 1.0 1 truesourceBase.union —Functionunion(s, itrs...)∪(s, itrs...)Construct an object containing all distinct elements from all of the arguments.
The first argument controls what kind of container is returned. If this is an array, it maintains the order in which elements first appear.
Unicode∪ can be typed by writing\cup then pressing tab in the Julia REPL, and in many editors. This is an infix operator, allowings ∪ itr.
See alsounique,intersect,isdisjoint,vcat,Iterators.flatten.
Examples
julia> union([1, 2], [3])3-element Vector{Int64}: 1 2 3julia> union([4 2 3 4 4], 1:3, 3.0)4-element Vector{Float64}: 4.0 2.0 3.0 1.0julia> (0, 0.0) ∪ (-0.0, NaN)3-element Vector{Real}: 0 -0.0 NaNjulia> union(Set([1, 2]), 2:3)Set{Int64} with 3 elements: 2 3 1sourceBase.union! —Functionunion!(s::IntDisjointSet{T}, x::T, y::T)Merge the subset containingx and that containingy into one and return the root of the new set.
Base.intersect —Functionintersect(s, itrs...)∩(s, itrs...)Construct the set containing those elements which appear in all of the arguments.
The first argument controls what kind of container is returned. If this is an array, it maintains the order in which elements first appear.
Unicode∩ can be typed by writing\cap then pressing tab in the Julia REPL, and in many editors. This is an infix operator, allowings ∩ itr.
See alsosetdiff,isdisjoint,issubset,issetequal.
As of Julia 1.8 intersect returns a result with the eltype of the type-promoted eltypes of the two inputs
Examples
julia> intersect([1, 2, 3], [3, 4, 5])1-element Vector{Int64}: 3julia> intersect([1, 4, 4, 5, 6], [6, 4, 6, 7, 8])2-element Vector{Int64}: 4 6julia> intersect(1:16, 7:99)7:16julia> (0, 0.0) ∩ (-0.0, 0)1-element Vector{Real}: 0julia> intersect(Set([1, 2]), BitSet([2, 3]), 1.0:10.0)Set{Float64} with 1 element: 2.0sourceBase.setdiff —FunctionBase.setdiff! —Functionsetdiff!(s, itrs...)Remove from sets (in-place) each element of each iterable fromitrs. Maintain order with arrays.
Examples
julia> a = Set([1, 3, 4, 5]);julia> setdiff!(a, 1:2:6);julia> aSet{Int64} with 1 element: 4sourceBase.symdiff —Functionsymdiff(s, itrs...)Construct the symmetric difference of elements in the passed in sets. Whens is not anAbstractSet, the order is maintained.
See alsosymdiff!,setdiff,union andintersect.
Examples
julia> symdiff([1,2,3], [3,4,5], [4,5,6])3-element Vector{Int64}: 1 2 6julia> symdiff([1,2,1], [2, 1, 2])Int64[]sourceBase.symdiff! —Functionsymdiff!(s::Union{AbstractSet,AbstractVector}, itrs...)Construct the symmetric difference of the passed in sets, and overwrites with the result. Whens is an array, the order is maintained. Note that in this case the multiplicity of elements matters.
Base.intersect! —Functionintersect!(s::Union{AbstractSet,AbstractVector}, itrs...)Intersect all passed in sets and overwrites with the result. Maintain order with arrays.
Base.in! —Functionin!(x, s::AbstractSet) -> BoolIfx is ins, returntrue. If not, pushx intos and returnfalse. This is equivalent toin(x, s) ? true : (push!(s, x); false), but may have a more efficient implementation.
Examples
julia> s = Set{Any}([1, 2, 3]); in!(4, s)falsejulia> length(s)4julia> in!(0x04, s)truejulia> sSet{Any} with 4 elements: 4 2 3 1sourceBase.issetequal —Functionissetequal(x)Create a function that compares its argument tox usingissetequal, i.e. a function equivalent toy -> issetequal(y, x). The returned function is of typeBase.Fix2{typeof(issetequal)}, which can be used to implement specialized methods.
issetequal(a, b) -> BoolDetermine whethera andb have the same elements. Equivalent toa ⊆ b && b ⊆ a but more efficient when possible.
See also:isdisjoint,union.
Examples
julia> issetequal([1, 2], [1, 2, 3])falsejulia> issetequal([1, 2], [2, 1])truesourceBase.isdisjoint —Functionisdisjoint(x)Create a function that compares its argument tox usingisdisjoint, i.e. a function equivalent toy -> isdisjoint(y, x). The returned function is of typeBase.Fix2{typeof(isdisjoint)}, which can be used to implement specialized methods.
isdisjoint(a, b) -> BoolDetermine whether the collectionsa andb are disjoint. Equivalent toisempty(a ∩ b) but more efficient when possible.
See also:intersect,isempty,issetequal.
Examples
julia> isdisjoint([1, 2], [2, 3, 4])falsejulia> isdisjoint([3, 1], [2, 4])truesourceFully implemented by:
Partially implemented by:
Base.push! —Functionpush!(collection, items...) -> collectionInsert one or moreitems incollection. Ifcollection is an ordered container, the items are inserted at the end (in the given order).
Examples
julia> push!([1, 2, 3], 4, 5, 6)6-element Vector{Int64}: 1 2 3 4 5 6Ifcollection is ordered, useappend! to add all the elements of another collection to it. The result of the preceding example is equivalent toappend!([1, 2, 3], [4, 5, 6]). ForAbstractSet objects,union! can be used instead.
Seesizehint! for notes about the performance model.
See alsopushfirst!.
Base.pop! —Functionpop!(collection, key[, default])Delete and return the mapping forkey if it exists incollection, otherwise returndefault, or throw an error ifdefault is not specified.
Examples
julia> d = Dict("a"=>1, "b"=>2, "c"=>3);julia> pop!(d, "a")1julia> pop!(d, "d")ERROR: KeyError: key "d" not foundStacktrace:[...]julia> pop!(d, "e", 4)4sourcepop!(collection) -> itemRemove an item incollection and return it. Ifcollection is an ordered container, the last item is returned; for unordered containers, an arbitrary element is returned.
See also:popfirst!,popat!,delete!,deleteat!,splice!, andpush!.
Examples
julia> A=[1, 2, 3]3-element Vector{Int64}: 1 2 3julia> pop!(A)3julia> A2-element Vector{Int64}: 1 2julia> S = Set([1, 2])Set{Int64} with 2 elements: 2 1julia> pop!(S)2julia> SSet{Int64} with 1 element: 1julia> pop!(Dict(1=>2))1 => 2sourceBase.popat! —Functionpopat!(a::Vector, i::Integer, [default])Remove the item at the giveni and return it. Subsequent items are shifted to fill the resulting gap. Wheni is not a valid index fora, returndefault, or throw an error ifdefault is not specified.
See also:pop!,popfirst!,deleteat!,splice!.
Examples
julia> a = [4, 3, 2, 1]; popat!(a, 2)3julia> a3-element Vector{Int64}: 4 2 1julia> popat!(a, 4, missing)missingjulia> popat!(a, 4)ERROR: BoundsError: attempt to access 3-element Vector{Int64} at index [4][...]sourceBase.pushfirst! —Functionpushfirst!(collection, items...) -> collectionInsert one or moreitems at the beginning ofcollection.
This function is calledunshift in many other programming languages.
Examples
julia> pushfirst!([1, 2, 3, 4], 5, 6)6-element Vector{Int64}: 5 6 1 2 3 4sourceBase.popfirst! —Functionpopfirst!(collection) -> itemRemove the firstitem fromcollection.
This function is calledshift in many other programming languages.
Examples
julia> A = [1, 2, 3, 4, 5, 6]6-element Vector{Int64}: 1 2 3 4 5 6julia> popfirst!(A)1julia> A5-element Vector{Int64}: 2 3 4 5 6sourceBase.deleteat! —Functiondeleteat!(a::Vector, inds)Remove the items at the indices given byinds, and return the modifieda. Subsequent items are shifted to fill the resulting gap.
inds can be either an iterator or a collection of sorted and unique integer indices, or a boolean vector of the same length asa withtrue indicating entries to delete.
Examples
julia> deleteat!([6, 5, 4, 3, 2, 1], 1:2:5)3-element Vector{Int64}: 5 3 1julia> deleteat!([6, 5, 4, 3, 2, 1], [true, false, true, false, true, false])3-element Vector{Int64}: 5 3 1julia> deleteat!([6, 5, 4, 3, 2, 1], (2, 2))ERROR: ArgumentError: indices must be unique and sortedStacktrace:[...]sourceBase.keepat! —Functionkeepat!(a::Vector, m::AbstractVector{Bool})keepat!(a::BitVector, m::AbstractVector{Bool})The in-place version of logical indexinga = a[m]. That is,keepat!(a, m) on vectors of equal lengtha andm will remove all elements froma for whichm at the corresponding index isfalse.
Examples
julia> a = [:a, :b, :c];julia> keepat!(a, [true, false, true])2-element Vector{Symbol}: :a :cjulia> a2-element Vector{Symbol}: :a :csourcekeepat!(a::Vector, inds)keepat!(a::BitVector, inds)Remove the items at all the indices which are not given byinds, and return the modifieda. Items which are kept are shifted to fill the resulting gaps.
inds must be an iterator of sorted and unique integer indices. See alsodeleteat!.
Examples
julia> keepat!([6, 5, 4, 3, 2, 1], 1:2:5)3-element Vector{Int64}: 6 4 2sourceBase.splice! —Functionsplice!(a::Vector, indices, [replacement]) -> itemsRemove items at specified indices, and return a collection containing the removed items. Subsequent items are shifted left to fill the resulting gaps. If specified, replacement values from an ordered collection will be spliced in place of the removed items; in this case,indices must be aAbstractUnitRange.
To insertreplacement before an indexn without removing any items, usesplice!(collection, n:n-1, replacement).
Examples
julia> A = [-1, -2, -3, 5, 4, 3, -1]; splice!(A, 4:3, 2)Int64[]julia> A8-element Vector{Int64}: -1 -2 -3 2 5 4 3 -1sourcesplice!(a::Vector, index::Integer, [replacement]) -> itemRemove the item at the given index, and return the removed item. Subsequent items are shifted left to fill the resulting gap. If specified, replacement values from an ordered collection will be spliced in place of the removed item.
See also:replace,delete!,deleteat!,pop!,popat!.
Examples
julia> A = [6, 5, 4, 3, 2, 1]; splice!(A, 5)2julia> A5-element Vector{Int64}: 6 5 4 3 1julia> splice!(A, 5, -1)1julia> A5-element Vector{Int64}: 6 5 4 3 -1julia> splice!(A, 1, [-1, -2, -3])6julia> A7-element Vector{Int64}: -1 -2 -3 5 4 3 -1To insertreplacement before an indexn without removing any items, usesplice!(collection, n:n-1, replacement).
Base.resize! —Functionresize!(a::Vector, n::Integer) -> VectorResizea to containn elements. Ifn is smaller than the current collection length, the firstn elements will be retained. Ifn is larger, the new elements are not guaranteed to be initialized.
Examples
julia> resize!([6, 5, 4, 3, 2, 1], 3)3-element Vector{Int64}: 6 5 4julia> a = resize!([6, 5, 4, 3, 2, 1], 8);julia> length(a)8julia> a[1:6]6-element Vector{Int64}: 6 5 4 3 2 1sourceBase.append! —Functionappend!(collection, collections...) -> collection.For an ordered containercollection, add the elements of eachcollections to the end of it.
Examples
julia> append!([1], [2, 3])3-element Vector{Int64}: 1 2 3julia> append!([1, 2, 3], [4, 5], [6])6-element Vector{Int64}: 1 2 3 4 5 6Usepush! to add individual items tocollection which are not already themselves in another collection. The result of the preceding example is equivalent topush!([1, 2, 3], 4, 5, 6).
Seesizehint! for notes about the performance model.
See alsovcat for vectors,union! for sets, andprepend! andpushfirst! for the opposite order.
Base.prepend! —Functionprepend!(a::Vector, collections...) -> collectionInsert the elements of eachcollections to the beginning ofa.
Whencollections specifies multiple collections, order is maintained: elements ofcollections[1] will appear leftmost ina, and so on.
Examples
julia> prepend!([3], [1, 2])3-element Vector{Int64}: 1 2 3julia> prepend!([6], [1, 2], [3, 4, 5])6-element Vector{Int64}: 1 2 3 4 5 6sourceFully implemented by:
Core.Pair —TypePair(x, y)x => yConstruct aPair object with typePair{typeof(x), typeof(y)}. The elements are stored in the fieldsfirst andsecond. They can also be accessed via iteration (but aPair is treated as a single "scalar" for broadcasting operations).
See alsoDict.
Examples
julia> p = "foo" => 7"foo" => 7julia> typeof(p)Pair{String, Int64}julia> p.first"foo"julia> for x in p println(x) endfoo7julia> replace.(["xops", "oxps"], "x" => "o")2-element Vector{String}: "oops" "oops"sourceBase.Pairs —TypeBase.Pairs(values, keys) <: AbstractDict{eltype(keys), eltype(values)}Transforms an indexable container into a Dictionary-view of the same data. Modifying the key-space of the underlying data may invalidate this object.
sourceSettings
This document was generated withDocumenter.jl version 1.16.0 onThursday 20 November 2025. Using Julia version 1.12.2.