ClojureDocs

Nav

Namespaces

nth

clojure.core

Available since 1.0 (source)
  • (nth coll index)
  • (nth coll index not-found)
Returns the value at the index. get returns nil if index out of
bounds, nth throws an exception unless not-found is supplied.  nth
also works for strings, Java arrays, regex Matchers and Lists, and,
in O(n) time, for sequences.
2 Examples
; Note that nth uses zero-based indexing, so that
;   (first my-seq) <=> (nth my-seq 0)
(def my-seq ["a" "b" "c" "d"])
(nth my-seq 0)
; => "a"
(nth my-seq 1)
; => "b"
(nth [] 0)
; => IndexOutOfBoundsException ...
(nth [] 0 "nothing found")
; => "nothing found"
(nth [0 1 2] 77 1337)
; => 1337
(nth ["last"] -1 "this is not perl")
; => "this is not perl"
See Also

Returns the first item in the collection. Calls seq on its argument. If coll is nil, returns nil...

Added by Havvy

Same as (first (next x))

Added by Havvy

Returns the nth next of coll, (seq coll) when n is 0.

Added by Havvy

Returns the value mapped to key, not-found or nil if key not present in associative collection, se...

Added by jw0

Returns a lazy seq of every nth item in coll. Returns a stateful transducer when no collection is...

Added by MicahElliott

Returns the nth rest of coll, coll when n is 0.

Added by MicahElliott

Return a random element of the (sequential) collection. Will have the same performance characteris...

Added by MicahElliott
2 Notes
    By , created 8.5 years ago

    Rather than throwing an exception, (nth nil n) returns nil for any number n.

    By , created 5.9 years ago

    Floats are treated as indexes (nth [0 1] 1.9) returns the element at index 1. At first glance it may seem as though they are always rounded down. However due to floating point precision (nth [0 1] 1.9999999999999999) will raise an IndexOutOfBoundsException.