In this shot, we'll learn how to use the List.nth
method to get a specific element in the nth
index.
It becomes hard to reach a particular element in a list by iterating the whole list from the start to that element. The easier way is to directly jump to the index of the required element.
List.nth
methodThe List.nth
method is used to get an element from a list at the nth
index. Always remember, the index of the list always starts from 0. For example, if we need to reach the third element of the list, we will provide an index as 2.
List.nth myList index
The List.nth
method receives a list
we want to work with and the index
of the element as parameters.
It returns the value of the element at the provided index
in the provided list
.
Let's look at the code below:
let myList = [4;5;6;7;2];;let myElement = List.nth myList 2;;print_int(myElement)
myList
.List.nth
method to get the second element of the list myList
and save it in a variable myElement
.print_int(myElement)
.