# 27 Lists

Lists are the most important way to collect objects and treat them together. A list is a collection of elements. A list also implies a partial mapping from the integers to the elements. I.e., there is a first element of a list, a second, a third, and so on.

List constants are written by writing down the elements in order between square brackets `[`, `]`, and separating them with commas `,`. An empty list, i.e., a list with no elements, is written as `[]`.

```    gap> [ 1, 2, 3 ];
[ 1, 2, 3 ]    # a list with three elements
gap> [ [], [ 1 ], [ 1, 2 ] ];
[ [  ], [ 1 ], [ 1, 2 ] ]    # a list may contain other lists ```

Usually a list has no holes, i.e., contain an element at every position. However, it is absolutely legal to have lists with holes. They are created by leaving the entry between the commas empty. Lists with holes are sometimes convenient when the list represents a mapping from a finite, but not consecutive, subset of the positive integers. We say that a list that has no holes is dense.

```    gap> l := [ , 4, 9,, 25,, 49,,,, 121 ];;
gap> l[3];
9
gap> l[4];
Error, List Element: <list>[4] must have a value ```

It is most common that a list contains only elements of one type. This is not a must though. It is absolutely possible to have lists whose elements are of different types. We say that a list whose elements are all of the same type is homogeneous.

```    gap> l := [ 1, E(2), Z(3), (1,2,3), [1,2,3], "What a mess" ];;
gap> l[1];  l[3];  l[5][2];
1
Z(3)
2 ```

The first sections describe the functions that test if an object is a list and convert an object to a list (see IsList and List).

The next section describes how one can access elements of a list (see List Elements and Length).

The next sections describe the operations applicable to lists (see Comparisons of Lists and Operations for Lists).

The next sections describe how one can find elements in a list (see In, Position, PositionSorted, PositionProperty).

The next sections describe the functions that construct new lists, e.g., sublists (see Concatenation, Flat, Reversed, Sublist, Cartesian).

The next sections describe the functions deal with the subset of elements of a list that have a certain property (see Number, Collected, Filtered, ForAll, ForAny, First).

The next sections describe the functions that sort lists (see Sort, SortParallel, Sortex, Permuted).

The next sections describe the functions to compute the product, sum, maximum, and minimum of the elements in a list (see Product, Sum, Maximum, Minimum, Iterated).

The final section describes the function that takes a random element from a list (see RandomList).

Lists are also used to represent sets, subsets, vectors, and ranges (see Sets, Boolean Lists, Vectors, and Ranges).

Previous Up Next
Index

GAP 3.4.4
April 1997