first

..  first(coll)

Get the first element of an iterable collection. Returns the start point of a :obj:`Range`
even if it is empty.

Examples

julia> foo = [1 2 3; 4 5 6]
2x3 Array{Int64,2}:
 1  2  3
 4  5  6
julia> first(foo)
1

julia> first([-1:-2:-10])
-1

julia> first(1:2:0)         # empty range
1

In the Julia programming language, the function first(coll) is used to retrieve the first element of an iterable collection. If the collection is empty, it returns the start point of a Range.

  1. Get the first element of an array:

    julia> arr = [1, 2, 3, 4];
    julia> first(arr)
    1

    This example returns the first element of the array arr.

  2. Retrieve the first element of a tuple:

    julia> tpl = (10, 20, 30);
    julia> first(tpl)
    10

    It returns the first element of the tuple tpl.

  3. Access the first element of a range:

    julia> rng = 1:5;
    julia> first(rng)
    1

    This example retrieves the start point of the range rng.

  4. Handling an empty collection:
    julia> empty_arr = Int[];
    julia> first(empty_arr)
    ERROR: ArgumentError: empty collection

    When the collection is empty, an ArgumentError is raised. It's important to handle such cases appropriately.

Common mistake example:

julia> str = "Hello";
julia> first(str)
'H'

In this example, the first function returns the first character of the string str as a character literal, not as a string. If you want the first character as a string, you can use first(string(str)) instead.

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.

*Required Field
Details

Checking you are not a robot: