Lists (1-D arrays) · Списки (1-мерные массивы)
A list holds many values
- A list keeps many values in one variable.
- Write the items inside square brackets:
[10, 20, 30]. - The items can be numbers, strings, or a mix.
Список хранит множество значений
- Список хранит множество значений в одной переменной.
- Запишите элементы внутри квадратных скобок:
[10, 20, 30]. - Элементами могут быть числа, строки или их комбинация.
Get and change items
- Use an index, just like a string:
nums[0]is the first item. nums[-1]is the last item.- You can also change an item:
nums[0] = 99.
Получение и изменение элементов
- Используйте индекс, как в строке:
nums[0]— это первый элемент. nums[-1]— это последний элемент.- Вы также можете изменить элемент:
nums[0] = 99.
fruits = ["apple", "pear", "plum"]
print(fruits[0])
print(fruits[-1])
Add items and count them
nums.append(x)addsxto the end of the list.len(nums)tells you how many items there are.- A list can grow as your program runs.
Добавление элементов и подсчет
nums.append(x)добавляетxв конец списка.len(nums)показывает количество элементов.- Список может расти во время выполнения программы.
fruits = ["apple", "pear"]
fruits.append("plum")
print(len(fruits))
print(fruits)
Loop over a list
for item in nums:visits each item in turn.- The loop variable holds one item per pass.
- This is the easy way to process every value.
Цикл по списку
for item in nums:посещает каждый элемент по очереди.- Переменная цикла хранит один элемент за итерацию.
- Это простой способ обработать каждое значение.
scores = [10, 20, 30]
total = 0
for s in scores:
total = total + s
print(total)
In Cambridge pseudocode
- A list is the exam's 1-D array. Note: exam arrays often start at index
1, but Python lists start at0.
В псевдокоде Cambridge
- Список — это 1-мерный массив экзамена. Примечание: массивы на экзаменах часто начинаются с индекса
1, но списки Python начинаются с0.
DECLARE Scores : ARRAY[1:3] OF INTEGER
Scores[1] ← 10
Scores[2] ← 20
Scores[3] ← 30
FOR I ← 1 TO 3
OUTPUT Scores[I]
NEXT I
Common mistakes
- The first item is
a[0]and the last isa[-1];a[len(a)]is out of range. b = adoes not copy the list — both names share it. Usea.copy()to make a real copy.appendadds one item to the end.
Распространенные ошибки
- Первый элемент —
a[0], а последний —a[-1];a[len(a)]выходит за пределы допустимого диапазона. b = aне копирует список — оба имени ссылаются на один и тот же объект. Используйтеa.copy()для создания реальной копии.appendдобавляет один элемент в конец.
Now you try
- Build or loop over a list in each task.
- Press Check answer to test your code.
Теперь попробуйте сами
- Создавайте или обходите список в каждом задании.
- Нажмите Check answer (Проверить ответ), чтобы протестировать свой код.
A list changes in place · Список изменяется на месте
A list is ordered and indexed; append/change/pop all modify it. · Список является упорядоченным и индексированным; операции append/change/pop изменяют его.
Create a list colors holding "red", "green", "blue". Then append "yellow" so the list has four items. · Создайте список colors, содержащий элементы "red", "green", "blue". Затем выполните операцию append ⟨⟩"yellow", чтобы в списке оказалось четыре элемента.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Loop over the list nums and add up its values. Store the total in total (the answer is 66). · Проходите по списку nums и суммируйте его значения. Сохраните итоговую сумму в total (ответ: 66).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Find the largest value in nums with a loop. Start largest at the first item, then loop through nums and keep the bigger value. Store the answer in largest (it is 23). · Найдите наибольшее значение в списке nums с помощью цикла. Начните со значения переменной largest, равного первому элементу, затем пройдите по списку nums, сохраняя большее значение. Сохраните результат в largest (это 23).
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.
Build a new list backwards with the items of nums in reverse order. Use a loop, and do not change nums itself. · Создайте новый список backwards с элементами из списка nums в обратном порядке. Используйте цикл и не изменяйте сам список nums.
Click Run to see the output here. · Нажмите Запустить, чтобы увидеть результат здесь.