CodeBlanks Logo Icon CodeBlanks

length and contains

Learn list info with .length and .contains.

length and contains

You find how many elements a List has with the .length property: [1, 2, 3].length evaluates to 3. You ask whether an element exists with the .contains() method: [1, 2, 3].contains(2) evaluates to true.

.length is a property (no parentheses); .contains() is a method (parentheses required). Both are common: length for loop bounds, contains for existence checks. For example if (cart.contains("Notebook")) checks whether the cart has a product.

Querying information

.length and .contains are two ways to query a list without changing it. With length you set a loop bound; with contains you check an element's existence. Neither mutates the original list.

For example in a shopping cart cart.length tells how many products there are; cart.contains("Notebook") tells whether a notebook is in the cart. Query methods are side-effect free; they only read. Practical tip: use non-mutating methods when querying information.

Practice Print length and contains

Declare a List with var numbers = [1, 2, 3];. Print the count with print(numbers.length);. Print whether 2 is in the list with print(numbers.contains(2));. The output must be two lines: 3 and true.

Starter code

main.dart
// Declare numbers, print length and contains

Sample solution

main.dart
var numbers = [1, 2, 3];
print(numbers.length);
print(numbers.contains(2));

Expected output

3
true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does [1, 2, 3].contains(2) return?

main.dart
[1, 2, 3].contains(2)
  • 2
  • 1
  • true Correct answer
  • -1

Explanation: 2 exists in the list; contains returns true.

2 Match each method to its job

Term Meaning
.length Element count
.contains(x) Exists (bool)
.add(x) Appends to end
[i] I-th element

3 Write the length call

Question
var numbers = [1, 2, 3];
print(numbers____);
Answer
var numbers = [1, 2, 3];
print(numbers.length);

Explanation: .length gives the element count of the List.

All lessons in Beginner