take
take(iter, n)
An iterator that generates at most the first n
elements of iter
.
Examples
-
Take the first
n
elements from an array:julia> arr = [1, 2, 3, 4, 5, 6]; julia> take(arr, 3) 3-element Array{Int64,1}: 1 2 3
This example takes the first 3 elements from the array
arr
and returns them as a new array. -
Create a limited range of numbers:
julia> numbers = 1:10; julia> take(numbers, 5) (1, 2, 3, 4, 5)
It generates a new tuple with the first 5 numbers from the range.
- Take elements from an iterator:
julia> iter = Base.Iterators.cycle(["A", "B", "C"]); julia> take(iter, 4) 4-element Array{String,1}: "A" "B" "C" "A"
In this example, it takes the first 4 elements from the cyclic iterator and returns them as an array.
Common mistake example:
julia> arr = [1, 2, 3, 4, 5];
julia> take(arr, 10)
ERROR: InexactError: trunc(Int64, 10.0)
In this example, the take
function throws an error because the requested number of elements is greater than the length of the array. Ensure that n
is within the valid range of the iterator or collection to avoid such errors.
See Also
countfrom, cycle, done, drop, eachindex, enumerate, first, repeated, rest, start, svds, take, vecdot, vecnorm, zip,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.