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



A del keyword can be used to delete list elements as well. In the example below, we have a list of strings. We use the del keyword to delete list elements.


Example 4

clrs = [“Red”, “Blue”, “Black”, “Green”, “White”]

print(clrs)

del clrs[1]

print(clrs)

Output

[‘Red’, ‘Blue’, ‘Black’, ‘Green’, ‘White’]

[‘Red’, ‘Black’, ‘Green’, ‘White’]

We remove the second string from the list. It is the “Blue” string.


Example 5

del clrs[:]

print(clrs)

Output

[]

Here we remove all the remaining elements from the list. The [ : ] characters refer to all items of a list.


Practice 2

1. Create and initialize a list;

2. Enter random 10 numbers into the list;

3. Remove 5 elements using different methods of removing;


Practice 3

There was a mistake! The amount of money you’ve earned is not that big after all and it looks like the pool house isn’t going to happen. You decide to remove the corresponding string and float from the areas list.

areas = [“hallway”, 11.25, “kitchen”, 18.0, “chill zone”, 20.0, “bedroom”, 10.75, “bathroom”, 10.50, “poolhouse”, 24.5, “garage”, 15.45]


Keep in mind

We can delete only existing elements. If we write del clrs[15], we will receive an IndexError message.


Literacy

1. Explain the differences between pop(), remove(), del and [ : ]?

2. What would happen if write pop() with the same index?

3. What would happen if we try to delete an item that doesn’t exist?


Terminology

remove – алып тастау – удалить

alphabetize – əліпбилік ретпен қою – располагать по алфавиту

corresponding – сəйкес келетін – соответствующий


3.7 TWO-DIMENSIONAL LIST IN PYTHON

You will:

create two-dimensional array in python;

use two-dimensional array.


In real-world often tasks have to store rectangular data table. How to write them in python list?

Список вложенный в список

Вы уже видели, что элемент в списке может быть объектом любого типа. Объект в списке также может иметь отдельный список, и элементы в этом списке тоже могут отдельным списком итд.


Example 1

>>> x = [‘a’, [‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’], ‘g’, [‘hh’, ‘ii’], ‘j’]

>>> x

[‘a’, [‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’], ‘g’, [‘hh’, ‘ii’], ‘j’]

The object structure that x references is diagrammed below:

x[0], x[2], and x[4] are strings, each one character long:

>>> print(x[0], x[2], x[4])

a g j

But x[1] and x[3] are sublists:

>>> x[1]


[‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’]

>>> x[3]

[‘hh’, ‘ii’]

To access the items in a sublist, simply append an additional index:

>>> x[1]

[‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’]