4.29 Built-in list operations
AllApplicationManualNameSummaryHelp

  • Documentation
    • Reference manual
      • Built-in Predicates
        • Built-in list operations
          • is_list/1
          • memberchk/2
          • length/2
          • sort/2
          • sort/4
          • msort/2
          • keysort/2
          • predsort/3
    • Packages
Availability:built-in
Source[ISO]length(?List, ?Length)
True if Length represents the number of elements in List. This predicate is a true relation and can be used to find the length of a list or produce a list (holding variables) of length Length. The predicate is non-deterministic, producing lists of increasing length if List is a partial list and Length is a variable.
?- length(List,4).
List = [_27940,_27946,_27952,_27958].

?- length(List,Length).
List = [], Length = 0 ;
List = [_24698], Length = 1 ;
List = [_24698,_25826], Length = 2
...

It raises errors if Length is bound to a non-integer or a negative integer or if List is neither a list nor a partial list. This error condition includes cyclic lists:137ISO demands failure here. We think an error is more appropriate.

?- A=[1,2,3|A], length(A,L).
ERROR: Type error: `list' expected ...

Covering an edge case, the predicate fails if the tail of List is equivalent to Length:138This is logically correct. An exception would be more appropriate, but to our best knowledge, current practice in Prolog does not describe a suitable candidate exception term.

?- List=[1,2,3|Length],length(List,Length).
false.

?- length(Length,Length).
false.