@Colin provided a compact, convenient answer. However, if speed matters (the operator is offered the most efficient way), this should be close to optimal
function findlongest(A) idx = 0 len = 0 @inbounds for i in 1:length(A) l = length(A[i]) l > len && (idx = i; len=l) end return A[idx] end
Note that this implementation (presumably) would be a very bad idea in Python :)
Quick test:
julia> using BenchmarkTools julia> A = [[1,2], [1,2,3,4,5,6], [1,2,3]] 3-element Array{Array{Int64,1},1}: [1, 2] [1, 2, 3, 4, 5, 6] [1, 2, 3] julia> @btime findlongest(A); 26.880 ns (0 allocations: 0 bytes) julia> @btime A[indmax(length.(A))]; 9.813 ฮผs (25 allocations: 1.14 KiB)
In this example, ~ 365 times faster .
EDIT: Best test (suggested in the comments)
julia> @btime findlongest($A); 9.813 ns (0 allocations: 0 bytes) julia> @btime $A[indmax(length.($A))]; 41.813 ns (1 allocation: 112 bytes)
The $ signs do not allow settings and time. Acceleration ~ 4.
Short description
- for loops fast in Julia so why not use them
- avoid selection (
length.(A) allocates a new array of integers) a && b is a shortcut for "if a then b"@inbounds avoids related checks for A[i]