Haskell Language Lists Accessing elements in lists


Access the nth element of a list (zero-based):

list = [1 .. 10]

firstElement = list !! 0           -- 1

Note that !! is a partial function, so certain inputs produce errors:

list !! (-1)     -- *** Exception: Prelude.!!: negative index  

list !! 1000     -- *** Exception: Prelude.!!: index too large

There's also Data.List.genericIndex, an overloaded version of !!, which accepts any Integral value as the index.

import Data.List (genericIndex)

list `genericIndex` 4              -- 5

When implemented as singly-linked lists, these operations take O(n) time. If you frequently access elements by index, it's probably better to use Data.Vector (from the vector package) or other data structures.