Lesson 16

Working with lists

Working with lists

In this lesson: you will search in a list, sort it and build new lists.

The whole lesson on one page

Working with lists

In this lesson: you will search in a list, sort it and build new lists.

Searching

1тағ номҳо = ["Алӣ", "Зарина", "Фарҳод"];
2чоп(номҳо.дорад("Зарина"));
3чоп(номҳо.индекси("Фарҳод"));
4чоп(номҳо.индекси("Сино"));
  • дорад(х) ("contains") tells whether х is in the list: дуруст or нодуруст.
  • индекси(х) gives the index of х, or -1 if it is not there.

Sorting

1тағ рақамҳо = [30, 4, 100, 25];
2рақамҳо.тартиб((а, б) => а - б);
3чоп(рақамҳо);

тартиб ("order") puts the numbers in order from the smallest to the largest if you give it (а, б) => а - б. This short function says which number comes first.

A new list: филтр and харита

1тағ холҳо = [55, 92, 47, 78, 30];
2тағ гузаштагон = холҳо.филтр(х => х >= 50);
3тағ дучанд = холҳо.харита(х => х * 2);
4чоп("Гузаштагон:", гузаштагон);
5чоп("Дучанд:", дучанд);
  • филтр keeps only the elements for which the condition is дуруст.
  • харита builds a new list from the function's result for each element; холҳо itself does not change.
  • х => х >= 50 is a short function: it takes х and returns х >= 50.

Task: Above the average

Read numbers into a list, find their average and print the numbers greater than the average in the same order, each on a separate line.

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

Output: The numbers greater than the average.

Task: Sorting

Read numbers into a list and print them from the smallest to the largest, each on a separate line.

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

Output: The numbers from the smallest to the largest.

Task: Search

Read numbers into a list, then the number to search for. Print its first index in the list, or -1 if it is not there.

Input: The first line is н, then н numbers, then the number to search for.

Output: The index or -1.

Task: No repeats

Read numbers into a list and print each number only once, in the order in which it first appears.

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

Output: The numbers without repeats.