Informatics 9. Билингвальный учебник | страница 21



Список представляет собой последовательность значений в квадратных скобках ([ ]). Значения списка называются элементами и разделяются запятыми.

>>> [value, value, ...]


Example 1

>>> data = [“This”, “list”, “has”, 4, “elements”]

>>> print (data)

This list has 4 elements

>>> numbers = [5, 3, 12, 4, 9, 12]

>>> print(numbers)

5 3 12 4 9 12


List Indexes

Each element in a list is accessed by an index. List indices start at 0.


An element can be accessed by an index using the following command:

list[index]


Example 2

>>> Fruits = [“apple”, “banana” , “orange”]

>>> print ( Fruits[0] )

>>> print ( Fruits[1] )

>>> print ( Fruits[2] )

apple banana orange


Keep in mind

Arrays and lists are both used in Python to store data, but they are different. The main difference between a list and an array is the functions that you can perform to them. Arrays have to be declared while lists don’t because they are part of Python’s syntax. So lists are used more often.


Practice 1

Print the second item in the fruits list.

fruits = [“apple”, “banana”, “cherry”]


Negative List Indexing

Virtually everything about string indexing works similarly for lists. For example, a negative list index counts from the end of the list:


Example 3

>>> a[-1]

‘corge’

>>> a[-2]

‘quux’

>>> a[-5]

‘bar’


Practice 2

Print the item with second negative index in the fruits list.

fruits = [“apple”, “banana”, “cherry”]


Negative List Indexing

In Python, lists can be modified. For example, you can change the element at a certain index by assigning a new value to it.

list[index] = value


Example 4

>>> Fruits = [“apple”,”banana”,”orange”]

>>> Fruits[0] = “peach”

>>> Fruits[1] = “cherry”

>>> print ( Fruits )

peach cherry orange


Practice 3

Change the value from “apple” to “kiwi”, in the fruits list.

fruits = [“apple”, “banana”, “cherry”]


Practice 4

There is a list of misspelled fruits within a list. Replace each mistake with the correct word.

fruits = [“aple”, “orang”, “bnanan”, “grapy”]


Literacy

1. Think about how to create a list of weekdays.

2. How can we change the start day of the week?


Terminology

index – индекс – индекс

element – элемент – элемент

array – массив – массив

comma – үтір – запятая

value – шама – значение

assign – тағайындау – присваивать

store – сақтау – хранить


3.2 CREATING AND ADDING ELEMENTS TO A LIST

You will:

Create python list and use;

Add and insert elements to the List.


Создание и чтение списков.

Списки в Python можно создать, просто поместив последовательность в квадратные скобки []. Список не нуждается во встроенной функции для создания списка.