# F# Lists

**F# lists** can be defined as collections of ordered values that have the same type and are of the same order.

F# list is an immutable object, which means that it cannot be modified once it has been created.

Operations on lists, on the other hand, return a new list that has the changes that were requested.

There are many functions available for creating, manipulating, and querying lists in F#, which makes them powerful and flexible.

A sequence of data, such as a list of names, numbers, or other values, can be represented by them.

There is a F# module named **Microsoft.FSharp.Collections.List** which has all of the common operations on lists. However, F# automatically imports this module into every F# application and makes it accessible to every single application written with F#.

By end of article you will learn how to create and manipulate F# lists of items, including how to insert and remove items, filter and sort lists, and perform operations on more than one list at a time.

## F# Lists Creation Methods

Here are some of the ways in which you can create a list:

Methods |
Overview |

Literals | By using list literals, we can create a list. |

(::) | By using the cons (::) operator, you can achieve this. |

List.init | The List module has a List.init method that can be used to start a list. |

syntactic construct | By utilizing a syntactic construct called List Comprehension. |

## List Literals

The list literal expresses a new list that will contain the values specified in the list literal expression.

List literals in F# are displayed as follows:

let list1 = [1; 2; 3; 4] let list2= ["apple"; "banana"; "cherry"]

## The Cons (::) Operator

A new list can be created by prepending an element to an existing list using the cons operator **::** in F#.

It is the shorthand form of the word “**construct**” and is pronounced as “**cons**“.

**::** accepts two operands: an element and a list.

An element is returned as part of a new list, which consists of the element and the elements from the original list that follow.

Here’s an example.

let list1 = 1 :: [2; 3; 4] let list2 = 1::2::3::4::5::6::7::8::9::10::[];;

The **[]** character denotes that the list is empty.

## List Init Method

Using the List.init method in F# is a way of creating a new list by applying a given function to the integers in a given range of values.

Here is what the syntax of List.init looks like:

val init : int -> (int -> 'T) -> 'T list

Firstly, there is an argument specifying the number of items to generate in the new list, and secondly there is an argument specifying the initializer function that is used to create the list’s items.

let stringList = List.init 5 (fun i -> "Item " + string i)

Here, String i function is used here to generate a list of strings.

## List Comprehensions

A F# list comprehension is a concise method to create additional lists of data from an existing sequence or list. The concept of list comprehension is based on the mathematical notation of set comprehension and can be used to map, combine, and filter elements.

For example,

let list1 = [1 .. 10]

There is a construct in generators which is: [for x in a collection do … yield expr],

For example,

let evenNumbers = [ for i in 1..10 do if i % 2 = 0 then yield i ]

In the same way that the yield keyword pushes some individual value into a list, yield! Is used to push a collection of values into the list.

Below is an example function demonstrating how the methods above can be used:

#### Example:

The output of the example above is as follows:

The list: [1; 2; 3; 4; 5; 6; 7; 8] The list: [1; 2; 3; 4; 5; 6] The list: [1; 2; 3; 4; 5; 6; 7; 8] The list: [a; b; c; d; e; f; g; h] The list: [0,0,0; 1,1,1; 2,4,8; 3,9,27; 4,16,64] The list: [1; 4; 9; 16; 25; 36; 49; 64] The list: [15; 30; 45; 60; 75; 90] The list: [1; 2; 3; 2; 3; 4]

## F# List Data Type

Below is a table that shows a variety of properties associated with list data types:

Property |
Type |
Overview |

Head | T | This is the first element of the list. |

Empty | T list | An empty list of the appropriate type can be returned by this static property as a result of the request. |

IsEmpty | bool | It is true if there are no elements in the list. |

Item | T | This element is at the index specified (zero-based). |

Length | int | Element count. |

Tail | T list | A list that does not contain the first element. |

Here is an example of how these properties can be used:

#### Example:

The results of all the above properties are printed as follows:

li.IsEmpty is false li.Length is 8 li.Head is 1 li.Tail.Head is 3 li.Tail.Tail.Head is 5 li.Item(1) is 3

## F# Lists Basic Operators

There are several basic operations you can perform on a list data type, as illustrated in the following table:

Value |
Overview |

append : ‘T list → ‘T list → ‘T list | The function returns a new list containing the elements of the first list followed by the elements of the second list at the end. |

average: ‘T list → ‘T list → ‘T list | The average element in the list of elements is returned as the result of this function. |

averageBy : (‘T → ^U) → ‘T list → ^U | By applying the function to each element of the list and taking the average of both elements, it will return the average of the elements generated. |

choose : (‘T → ‘U option) → ‘T list → ‘U list | The given function will be applied to every element of the list one by one. This function will return a list of each element’s result for each element where the function returns Some as a result. |

Collect : (‘T → ‘U list) → ‘T list → ‘U list | This function will be applied to each element of the list, one at a time. Return the combined list of all the results after concatenating all of them together. |

concat : seq<‘T list> → ‘T list | A new list will be returned which will contain the elements of all of the lists, sorted alphabetically. |

empty : ‘T list | The function returns an empty list with the given type as its value. |

exists : (‘T → bool) → ‘T list → bool | The function checks if any element from the list meets the given predicate by checking whether it is present. |

exists2 : (‘T1 → ‘T2 → bool) → ‘T1 list → ‘T2 list → bool | In this function, it is tested to see if a pair of corresponding elements in the lists is satisfied by the given predicate. |

filter : (‘T → bool) → ‘T list → ‘T list | In this function, a new collection is returned that contains only those elements of the original collection for which the given predicate corresponds to true. |

find : (‘T → bool) → ‘T list → ‘T | It returns the element that is the first element to return true when the given function is used. |

findIndex : (‘T → bool) → ‘T list → int | A predicate that is satisfied by the first element in the list is returned. |

fold : (‘State → ‘T → ‘State) → ‘State → ‘T list → ‘State | This function threads an accumulator argument through each element of the collection. It applies the function to the second argument and the first element of the list. This result will then be passed by the program along with the second element, and the process will continue in this way. It then returns the final result. A function f is given, and the elements are i0…iN, so this function computes f (… (f s i0) i1 …) iN. |

fold2 : (‘State → ‘T1 → ‘T2 → ‘State) → ‘State → ‘T1 list → ‘T2 list → ‘State | This function applies a function to the elements of two collections that correspond to each other, and threads an accumulator argument through the computation as well. There must be identical collections. Using i0…iN and j0…jN as input functions, this function computes f (… (f s i0 j0)…) iN jN. |

foldBack : (‘T → ‘State → ‘State) → ‘T list → ‘State → ‘State | This function applies a function to every element in the collection, through which an accumulator argument is passed through the computation for each element. A function f is passed as an input, and the input elements i0…iN are passed as input which computes f i0 (…(f iN s)). |

foldBack2 : (‘T1 → ‘T2 → ‘State → ‘State) → ‘T1 list → ‘T2 list → ‘State → ‘State | In this function, an element of two collections is threaded through the computation and a function reference is passed as an argument. Collections must be identical. A function f is passed to this function and if the elements in each case are i0…iN and j0…jN, then this function will compute the value of f i0 j0 (…(f iN jN s )). |

forall : (‘T → bool) → ‘T list → bool | This function checks if all elements satisfy the given predicate in the collection. |

forall : (‘T → bool) → ‘T list → bool | Identifies whether all elements corresponding to the given predicate are satisfied pairwise in the collection. |

head : ‘T list → ‘T | It is used to return the first element in a list. |

init : int → (int → ‘T) → ‘T list | The function creates a list by using the given generator as an index on each item in the list. |

isEmpty : ‘T list → bool | This method returns true if the list does not contain any elements, and false if it does. |

iter : (‘T → unit) → ‘T list → unit | Every element in the collection will be applied with the given function. |

iter2 : (‘T1 → ‘T2 → unit) → ‘T1 list → ‘T2 list → unit | The given function is applied simultaneously to two collections. There must be an identical size between the two collections. |

iteri : (int → ‘T → unit) → ‘T list → unit | Each element in the collection is applied to the given function. Integers passed to the function indicate element indexes. |

iteri2 : (int → ‘T1 → ‘T2 → unit) → ‘T1 list → ‘T2 list → unit | The given function will be applied simultaneously to two collections. There must be an equal size between the two collections. This integer indicates the index of the element that has been passed to the function. |

length : ‘T list → int | The length of the list is returned by this function. |

map : (‘T → ‘U) → ‘T list → ‘U list | In this method, the elements of a collection are the results of applying a given function to each element of a collection, and the result is returned as the elements of a new collection. |

map2 : (‘T1 → ‘T2 → ‘U) → ‘T1 list → ‘T2 list → ‘U list | In this method, a new collection is created whose elements correspond to the respective elements of the two sets of collections if the given function is applied pairwise to the corresponding elements of the two sets. |

map3 : (‘T1 → ‘T2 → ‘T3 → ‘U) → ‘T1 list → ‘T2 list → ‘T3 list → ‘U list | In this function, the three collections are applied simultaneously to their corresponding elements to produce a new collection. |

mapi : (int → ‘T → ‘U) → ‘T list → ‘U list | Applying a given function to each element of the collection creates a new collection whose elements are the results of the application. This integer index represents the element’s index (from 0) when passed to the function. |

mapi2 : (int → ‘T1 → ‘T2 → ‘U) → ‘T1 list → ‘T2 list → ‘U list | This is similar to List.mapi, but it maps the elements of two lists with the same length to each other. |

max : ‘T list → ‘T | By using Operators.max, this function returns the greatest value among all of the elements in the list. |

maxBy : (‘T → ‘U) → ‘T list → ‘T | The function returns the greatest element in the list among all the elements of the list, comparing the result of the function with its Operators.max method. |

min : ‘T list → ‘T | This function returns the lowest element in a list, compared using Operators.min as a comparison method. |

minBy : (‘T → ‘U) → ‘T list → ‘T | Using Operators.min on the result of the function, this function returns the lowest element within all the elements of the list |

nth : ‘T list → int → ‘T | The index of each item in the list. 0 is the index of the first element in the list. |

ofArray : ‘T [] → ‘T list | From an array of items, a list can be created. |

ofSeq : seq<‘T> → ‘T list | Provides a new list based on the enumerable object given to it. |

partition : (‘T → bool) → ‘T list * ‘T list | This method splits a collection into two collections containing elements that return true or false based on the given predicate. |

permute : (int → int) → ‘T list → ‘T list | Specifies a permutation method that returns a list with all elements permuted. |

pick : (‘T → ‘U option) → ‘T list → ‘U | Returns the first result when the given function returns Some for some value when applied to successive elements. |

reduce : (‘T → ‘T → ‘T) → ‘T list → ‘T | This function is applied to each element of the collection, and an accumulator argument is passed to the function when the computation is performed. The first two elements of the list are subjected to the specified function. The result is then passed into the function with the third element and so on. Lastly, it returns the final result. Suppose that the input function is f and the input elements are i0…iN, then the function will compute f (… (f i0 i1) i2 …) iN for the specified input function. |

reduceBack : (‘T → ‘T → ‘T) → ‘T list → ‘T | The function is applied to each element of the collection, and then an accumulator argument is passed through the computation to control the operation. A function f is inputted, and the elements will be i0…iN, then the function will calculate f i0 (…(f iN-1 iN)). |

replicate : (int → ‘T → ‘T list) | The function creates a list by using the given generator as an index on each item in the list. |

rev : ‘T list → ‘T list | There is a function that returns a new list that has the elements in reversed order. |

scan : (‘State → ‘T → ‘State) → ‘State → ‘T list → ‘State list | A function is applied to each element of the collection, threading the computation through the accumulator argument associated with each element. With this function, we can take the second argument and apply the function specified to it along with the first element of the list. Following this, the result of the calculation is passed into the function along with the second element, and so on. At the end, it returns both the intermediate and final results. |

scanBack : (‘T → ‘State → ‘State) → ‘T list → ‘State → ‘State list | The result is both the intermediate and final results, just like foldBack. |

sort : ‘T list → ‘T list | By using Operators.compare, this function sorts the list given to it. |

sortBy : (‘T → ‘Key) → ‘T list → ‘T list | The given list is sorted using the keys provided by the projection given in the input. Using the Operators.compare method, keys are compared between each other. |

sortWith : (‘T → ‘T → int) → ‘T list → ‘T list | This function uses the comparison function provided in the given list to sort the given list. |

sum : ^T list → ^T | Calculates the sum of elements in a list. |

sumBy : (‘T → ^U) → ‘T list → ^U | Each list element’s result is returned as a sum when the function is applied. |

tail : ‘T list → ‘T list | A list of input elements without the first element is returned. |

toArray : ‘T list → ‘T [] | The function creates an array from a list given to it. |

toSeq : ‘T list → seq<‘T> | Provides a sequence view of the given list. |

tryFind : (‘T → bool) → ‘T list → ‘T option | Provides a list of elements for which a function returns true based on the given parameters. If there is no such element, the return value will be None. |

tryFindIndex : (‘T → bool) → ‘T list → int option | There will be an index returned that represents the position in the list of the first element that meets the given predicate. If there is no such element, then return None. |

tryPick : (‘T → ‘U option) → ‘T list → ‘U option | As we apply successive elements to the given function, it returns a first result when the function returns Some for a certain value. The return value should be None if such an element does not exist. |

unzip : (‘T1 * ‘T2) list → ‘T1 list * ‘T2 list | This function is used to split a list of pairs into two lists. |

unzip3 : (‘T1 * ‘T2 * ‘T3) list → ‘T1 list * ‘T2 list * ‘T3 list | The function splits a list of triples into three separate lists. |

zip : ‘T1 list → ‘T2 list → (‘T1 * ‘T2) list | This function is used to combine the two lists into a list of pairs. There must be an equal length between the two lists. |

zip3 : ‘T1 list → ‘T2 list → ‘T3 list → (‘T1 * ‘T2 * ‘T3) list | A list of triples is formed by combining the three lists. There must be an equal length between the lists. |

## F# Lists Reversing

Here is a program that shows how to reverse a list recursively:

#### Example:

And the output will be:

If you need to do the same thing, you could use the **List.rev** function of the module as follows:

#### Example:

**Output:**

## F# List.average

Below is an example of calculating the average of all elements in the list by using** List.average**:

#### Example:

And the result is:

## F# List Filter

In the following program, you will be able to see how to filter a list using the **List.filter** method.

#### Example:

Filtering results of the list are as follows:

## F# List Map

The **List.map** method is used to map a list between two types:

#### Example:

Mapping the list into different types outputs as follows:

## F# List Sorting

Lists can be sorted by using the **List.sort** method.

#### Example:

As a result of sorting the list, here is what the output will look like:

## F# List Append

**List.append** is a method that combines two lists and appends them to each other:

#### Example:

The output will be as follows:

The first list: [2; 4; 58; 85; 12] The second list: [6; 5; 4; 3; 2] The appened list: [2; 4; 58; 85; 12; 6; 5; 4; 3; 2]

## F# List.Sum

**List.sum** is a method that returns the sum of the elements in a list

#### Example:

The sum of all elements is:

The sum: 161

## F# List.Fold

In the **List.fold** method, a function is applied from left to right to each element of the List:

#### Example:

The output will be as follows:

### Example Explanation

This F# code defines a list of integers numbers with the values **[2; 1; 5; 6; 8]**. It then uses the **List.fold** function to calculate the sum of the elements in the list, which is stored in the variable sum. The initial value of the accumulator **acc is set to 2**.

The List.fold function takes three arguments: a function that specifies how to combine the accumulator with each element of the list, an initial value for the accumulator, and the list itself.

In this case, the lambda function passed as the first argument to List.fold takes two arguments: acc and x. It returns the sum of acc and x, which is used as the new accumulator value. The accumulator’s initial value is 2.

The List.fold function applies the lambda function to each list element and updates the accumulator accordingly. It starts with an initial accumulator value of 2, and then **adds 2** to each element in the list, resulting in a final accumulator value of **2 + 2 + 1 + 5 + 6 + 8**, which is **24**.

Finally, the code uses the printfn function to print out the results. This program would output:

The sum of the numbers is: 24

If you liked this article and found it informative regarding F# functional programming language, you can leave your feedback by reacting below.