How to find the length of a list in OCaml

Overview

Most of the time, we want to dynamically loop through a list by using the list's length. The best way to do it is by getting the length of the list first. In this shot, we learn to get the length of the list using the List.length method in OCaml.

What is the List.length method?

The List.length method gets the number of items in a list.

Syntax

List.length list
The syntax of the List.length method

Parameter

This List.length method receives a list.

Return value

The List.length method returns the total number of the items in a list. Let's see an example.

Code

let x = [3;4;5;7;8;9;0];;
print_int(List.length x)

Explanation

Line 1: We define and initialize our list, x.

Line 2: We print the length of the list x using the List.length method in print_int().

New on Educative
Learn any Language for FREE all September 🎉
For the entire month of September, get unlimited access to our entire catalog of beginner coding resources.
🎁 G i v e a w a y
30 Days of Code
Complete Educative’s daily coding challenge every day in September, and win exciting Prizes.

Free Resources