Lesson 15

Lists

Lists

In this lesson: you will keep several values in one list.

The whole lesson on one page

Lists

In this lesson: you will keep several values in one list.

What is a list?

A list (рӯйхат) keeps several values in order. You write it in square brackets [ ]:

1тағ холҳо = [5, 4, 5, 3];
2чоп(холҳо);
3чоп("Аввалин:", холҳо[0]);
4чоп("Дуюмин:", холҳо[1]);
5чоп("Шумора:", холҳо.дарозӣ);
  • Each value in a list is an element (унсур). The number of an element, its index, starts at 0: the first element is холҳо[0].
  • холҳо.дарозӣ ("length") is the number of elements. The last element is холҳо[холҳо.дарозӣ - 1].

Change and add

1тағ меваҳо = ["себ", "нок"];
2меваҳо[0] = "анор";
3меваҳо.илова("ангур");
4чоп(меваҳо);
5чоп(меваҳо.дарозӣ);

илова ("add") adds an element to the end of the list.

A loop over a list

барои (тағ х аз рӯйхат) takes the elements one by one:

1тағ холҳо = [5, 4, 5, 3, 4];
2тағ ҷамъ = 0;
3барои (тағ хол аз холҳо) {
4 ҷамъ += хол;
5}
6чоп("Миёна:", ҷамъ / холҳо.дарозӣ);

Fill a list from the input

First the number of elements, then the elements themselves, each on its own line:

1тағ н = хонданиРақам();
2тағ рақамҳо = [];
3барои (тағ и = 0; и < н; и++) {
4 рақамҳо.илова(хонданиРақам());
5}
6чоп(рақамҳо);
Input
3
10
20
30

Common mistakes

  • The index starts at 0, not at 1.
  • An element outside the list: холҳо[10] gives беқимат (no value), and холҳо[10].дарозӣ gives an error while the program runs.

Task: Sum of a list

Read numbers into a list and print their sum.

Input: The first line is the count of numbers н, then н lines with one number each.

Output: The sum.

Task: The greatest in a list

Read numbers into a list and print the greatest of them.

Input: The first line is the count of numbers н, then н lines with one number each.

Output: The greatest.

Task: Backwards

Read numbers into a list and print them in reverse order, each on a separate line.

Input: The first line is the count of numbers н, then н lines with one number each.

Output: The numbers in reverse order.

Task: Number of even numbers

Read numbers into a list and print how many of them are even.

Input: The first line is the count of numbers н, then н lines with one number each.

Output: The number of even numbers.