5. Data Structures¶
This chapter describes some things you’ve learned about already in more detail, and adds some new things as well.
5.1. More on Lists¶
The list data type has some more methods. Here are all of the methods of list objects:
Add an item to the end of the list. Equivalent to a[len(a):] = [x] .
list. extend ( iterable )
Extend the list by appending all the items from the iterable. Equivalent to a[len(a):] = iterable .
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x) .
Remove the first item from the list whose value is equal to x. It raises a ValueError if there is no such item.
Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
Remove all items from the list. Equivalent to del a[:] .
Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.
The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.
Return the number of times x appears in the list.
list. sort ( * , key = None , reverse = False )
Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).
Reverse the elements of the list in place.
Return a shallow copy of the list. Equivalent to a[:] .
An example that uses most of the list methods:
You might have noticed that methods like insert , remove or sort that only modify the list have no return value printed – they return the default None . 1 This is a design principle for all mutable data structures in Python.
Another thing you might notice is that not all data can be sorted or compared. For instance, [None, ‘hello’, 10] doesn’t sort because integers can’t be compared to strings and None can’t be compared to other types. Also, there are some types that don’t have a defined ordering relation. For example, 3+4j < 5+7j isn’t a valid comparison.
5.1.1. Using Lists as Stacks¶
The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved (“last-in, first-out”). To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index. For example:
5.1.2. Using Lists as Queues¶
It is also possible to use a list as a queue, where the first element added is the first element retrieved (“first-in, first-out”); however, lists are not efficient for this purpose. While appends and pops from the end of list are fast, doing inserts or pops from the beginning of a list is slow (because all of the other elements have to be shifted by one).
To implement a queue, use collections.deque which was designed to have fast appends and pops from both ends. For example:
5.1.3. List Comprehensions¶
List comprehensions provide a concise way to create lists. Common applications are to make new lists where each element is the result of some operations applied to each member of another sequence or iterable, or to create a subsequence of those elements that satisfy a certain condition.
For example, assume we want to create a list of squares, like:
Note that this creates (or overwrites) a variable named x that still exists after the loop completes. We can calculate the list of squares without any side effects using:
which is more concise and readable.
A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it. For example, this listcomp combines the elements of two lists if they are not equal:
and it’s equivalent to:
Note how the order of the for and if statements is the same in both these snippets.
If the expression is a tuple (e.g. the (x, y) in the previous example), it must be parenthesized.
List comprehensions can contain complex expressions and nested functions:
5.1.4. Nested List Comprehensions¶
The initial expression in a list comprehension can be any arbitrary expression, including another list comprehension.
Consider the following example of a 3×4 matrix implemented as a list of 3 lists of length 4:
The following list comprehension will transpose rows and columns:
As we saw in the previous section, the inner list comprehension is evaluated in the context of the for that follows it, so this example is equivalent to:
which, in turn, is the same as:
In the real world, you should prefer built-in functions to complex flow statements. The zip() function would do a great job for this use case:
See Unpacking Argument Lists for details on the asterisk in this line.
5.2. The del statement¶
There is a way to remove an item from a list given its index instead of its value: the del statement. This differs from the pop() method which returns a value. The del statement can also be used to remove slices from a list or clear the entire list (which we did earlier by assignment of an empty list to the slice). For example:
del can also be used to delete entire variables:
Referencing the name a hereafter is an error (at least until another value is assigned to it). We’ll find other uses for del later.
5.3. Tuples and Sequences¶
We saw that lists and strings have many common properties, such as indexing and slicing operations. They are two examples of sequence data types (see Sequence Types — list, tuple, range ). Since Python is an evolving language, other sequence data types may be added. There is also another standard sequence data type: the tuple.
A tuple consists of a number of values separated by commas, for instance:
As you see, on output tuples are always enclosed in parentheses, so that nested tuples are interpreted correctly; they may be input with or without surrounding parentheses, although often parentheses are necessary anyway (if the tuple is part of a larger expression). It is not possible to assign to the individual items of a tuple, however it is possible to create tuples which contain mutable objects, such as lists.
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable , and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples ). Lists are mutable , and their elements are usually homogeneous and are accessed by iterating over the list.
A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective. For example:
The statement t = 12345, 54321, ‘hello!’ is an example of tuple packing: the values 12345 , 54321 and ‘hello!’ are packed together in a tuple. The reverse operation is also possible:
This is called, appropriately enough, sequence unpacking and works for any sequence on the right-hand side. Sequence unpacking requires that there are as many variables on the left side of the equals sign as there are elements in the sequence. Note that multiple assignment is really just a combination of tuple packing and sequence unpacking.
5.4. Sets¶
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements. Basic uses include membership testing and eliminating duplicate entries. Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set() , not <> ; the latter creates an empty dictionary, a data structure that we discuss in the next section.
Here is a brief demonstration:
Similarly to list comprehensions , set comprehensions are also supported:
5.5. Dictionaries¶
Another useful data type built into Python is the dictionary (see Mapping Types — dict ). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend() .
It is best to think of a dictionary as a set of key: value pairs, with the requirement that the keys are unique (within one dictionary). A pair of braces creates an empty dictionary: <> . Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del . If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
Performing list(d) on a dictionary returns a list of all the keys used in the dictionary, in insertion order (if you want it sorted, just use sorted(d) instead). To check whether a single key is in the dictionary, use the in keyword.
Here is a small example using a dictionary:
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
5.6. Looping Techniques¶
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
When looping through a sequence, the position index and corresponding value can be retrieved at the same time using the enumerate() function.
To loop over two or more sequences at the same time, the entries can be paired with the zip() function.
To loop over a sequence in reverse, first specify the sequence in a forward direction and then call the reversed() function.
To loop over a sequence in sorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
Using set() on a sequence eliminates duplicate elements. The use of sorted() in combination with set() over a sequence is an idiomatic way to loop over unique elements of the sequence in sorted order.
It is sometimes tempting to change a list while you are looping over it; however, it is often simpler and safer to create a new list instead.
5.7. More on Conditions¶
The conditions used in while and if statements can contain any operators, not just comparisons.
The comparison operators in and not in are membership tests that determine whether a value is in (or not in) a container. The operators is and is not compare whether two objects are really the same object. All comparison operators have the same priority, which is lower than that of all numerical operators.
Comparisons can be chained. For example, a < b == c tests whether a is less than b and moreover b equals c .
Comparisons may be combined using the Boolean operators and and or , and the outcome of a comparison (or of any other Boolean expression) may be negated with not . These have lower priorities than comparison operators; between them, not has the highest priority and or the lowest, so that A and not B or C is equivalent to (A and (not B)) or C . As always, parentheses can be used to express the desired composition.
The Boolean operators and and or are so-called short-circuit operators: their arguments are evaluated from left to right, and evaluation stops as soon as the outcome is determined. For example, if A and C are true but B is false, A and B and C does not evaluate the expression C . When used as a general value and not as a Boolean, the return value of a short-circuit operator is the last evaluated argument.
It is possible to assign the result of a comparison or other Boolean expression to a variable. For example,
Note that in Python, unlike C, assignment inside expressions must be done explicitly with the walrus operator := . This avoids a common class of problems encountered in C programs: typing = in an expression when == was intended.
5.8. Comparing Sequences and Other Types¶
Sequence objects typically may be compared to other objects with the same sequence type. The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted. If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively. If all items of two sequences compare equal, the sequences are considered equal. If one sequence is an initial sub-sequence of the other, the shorter sequence is the smaller (lesser) one. Lexicographical ordering for strings uses the Unicode code point number to order individual characters. Some examples of comparisons between sequences of the same type:
Note that comparing objects of different types with < or > is legal provided that the objects have appropriate comparison methods. For example, mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc. Otherwise, rather than providing an arbitrary ordering, the interpreter will raise a TypeError exception.
Other languages may return the mutated object, which allows method chaining, such as d->insert("a")->remove("b")->sort(); .
Список
Список — это непрерывная динамическая коллекция элементов. Каждому элементу списка присваивается порядковый номер — его индекс. Первый индекс равен нулю, второй — единице и так далее. Основные операции для работы со списками — это индексирование, срезы, добавление и удаление элементов, а также проверка на наличие элемента в последовательности.
Создание пустого списка выглядит так:
Создадим список, состоящий из нескольких чисел:
numbers = [ 40 , 20 , 90 , 11 , 5 ]
Настало время строковых переменных:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
Не будем забывать и о дробях:
fractions = [ 3.14 , 2.72 , 1.41 , 1.73 , 17.9 ]
Мы можем создать список, состоящий из различных типов данных:
values = [ 3.14 , 10 , ‘Hello world!’ , False, ‘Python is the best’ ]
И такое возможно (⊙_⊙)
list_of_lists = [[ 2 , 4 , 0 ], [ 11 , 2 , 10 ], [ 0 , 19 , 27 ]]
Индексирование
Что же такое индексирование? Это загадочное слово обозначает операцию обращения к элементу по его порядковому номеру ( ( ・ω・)ア напоминаю, что нумерация начинается с нуля). Проиллюстрируем это на примере:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[ 0 ])
print (fruits[ 1 ])
print (fruits[ 4 ])
Списки в Python являются изменяемым типом данных. Мы можем изменять содержимое каждой из ячеек:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
fruits[ 0 ] = ‘Watermelon’
fruits[ 3 ] = ‘Lemon’
print (fruits)
>>> [ ‘Watermelon’ , ‘Grape’ , ‘Peach’ , ‘Lemon’ , ‘Orange’ ]
Индексирование работает и в обратную сторону. Как такое возможно? Всё просто, мы обращаемся к элементу списка по отрицательному индексу. Индекс с номером -1 дает нам доступ к последнему элементу, -2 к предпоследнему и так далее.
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[ -1 ])
print (fruits[ -2 ])
print (fruits[ -3 ])
print (fruits[ -4 ])
Создание списка с помощью list()
Переходим к способам создания списка. Самый простой из них был приведен выше. Еще раз для закрепления:
А есть еще способы? Да, есть. Один из них — создание списка с помощью функции list() В неё мы можем передать любой итерируемый объект (да-да, тот самый по которому можно запустить цикл (• ᵕ •) )
Рассмотрим несколько примеров:
letters = list ( ‘abcdef’ )
numbers = list ( range ( 10 ))
even_numbers = list ( range ( 0 , 10 , 2 ))
print (letters)
print (numbers)
print (even_numbers)
>>> [ ‘a’ , ‘b’ , ‘c’ , ‘d’ , ‘e’ , ‘f’
>>> [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
>>> [ 0 , 2 , 4 , 6 , 8 ]
Длина списка
С созданием списка вроде разобрались. Следующий вопрос: как узнать длину списка? Можно, конечно, просто посчитать количество элементов. (⊙_⊙) Но есть способ получше! Функция len() возвращает длину любой итерируемой переменной, переменной, по которой можно запустить цикл. Рассмотрим пример:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print ( len (fruits))
numbers = [ 40 , 20 , 90 ]
print ( len (numbers))
«. любой итерируемой», а это значит:
string = ‘Hello world’
print ( len (string))
# 11
print ( len ( range ( 10 ))
Срезы
В начале статьи что-то говорилось о «срезах». Давайте разберем подробнее, что это такое. Срезом называется некоторая подпоследовательность. Принцип действия срезов очень прост: мы «отрезаем» кусок от исходной последовательности элемента, не меняя её при этом. Я сказал «последовательность», а не «список», потому что срезы работают и с другими итерируемыми типами данных, например, со строками.
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
part_of_fruits = fruits[ 0 :3]
print (part_of_fruits)
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ ]
Детально рассмотрим синтаксис срезов:
итерируемая_переменная[начальный_индекс:конечный_индекс — 1 :длина_шага]
Обращаю ваше внимание, что мы делаем срез от начального индекса до конечного индекса — 1. То есть i = начальный_индекс и i = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[ 0 :1])
# Если начальный индекс равен 0, то его можно опустить
print (fruits[: 2 ])
print (fruits[: 3 ])
print (fruits[: 4 ])
print (fruits[: 5 ])
# Если конечный индекс равен длине списка, то его тоже можно опустить
print (fruits[: len (fruits)])
print (fruits[::])
>>> [ ‘Apple’ ]
>>> [ ‘Apple’ , ‘Grape’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
>>> [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
Самое время понять, что делает третий параметр среза — длина шага!
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
print (fruits[:: 2 ])
print (fruits[:: 3 ])
# Длина шага тоже может быть отрицательной!
print (fruits[:: -1 ])
print (fruits[ 4 :2: -1 ])
print (fruits[ 3 :1: -1 ])
>>> [ ‘Apple’ , ‘Peach’ , ‘Orange’ ]
>>> [ ‘Apple’ , ‘Banan’ ]
>>> [ ‘Orange’ , ‘Banan’ , ‘Peach’ , ‘Grape’ , ‘Apple’ ]
>>> [ ‘Orange’ , ‘Banan’ ]
>>> [ ‘Banan’ , ‘Peach’ ]
А теперь вспоминаем всё, что мы знаем о циклах. В Python их целых два! Цикл for и цикл while Нас интересует цикл for, с его помощью мы можем перебирать значения и индексы наших последовательностей. Начнем с перебора значений:
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
f or fruit in fruits:
print (fruit, end = ‘ ‘ )
>>> Apple Grape Peach Banan Orange
Выглядит несложно, правда? В переменную fruit объявленную в цикле по очереди записываются значения всех элементов списка fruits
А что там с перебором индексов?
f or index in range ( len (fruits)):
print (fruits[index], end = ‘ ‘ )
Этот пример гораздо интереснее предыдущего! Что же здесь происходит? Для начала разберемся, что делает функция range(len(fruits))
Мы с вами знаем, что функция len() возвращает длину списка, а range() генерирует диапазон целых чисел от 0 до len()-1.
Сложив 2+2, мы получим, что переменная index принимает значения в диапазоне от 0 до len()-1. Идем дальше, fruits[index] — это обращение по индексу к элементу с индексом index списка fruits. А так как переменная index принимает значения всех индексов списка fruits, то в цикле мы переберем значения всех элементов нашего списка!
Операция in
С помощью in мы можем проверить наличие элемента в списке, строке и любой другой итерируемой переменной.
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
if ‘Apple’ in fruits:
print ( ‘В списке есть элемент Apple’ )
>>> В списке есть элемент Apple
fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
if ‘Lemon’ in fruits:
print ( ‘В списке есть элемент Lemon’ )
else :’
print ( ‘В списке НЕТ элемента Lemon’ )
>>> В списке НЕТ элемента Lemon
Приведу более сложный пример:
all_fruits = [ ‘Apple’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Orange’ ]
my_favorite_fruits = [ ‘Apple’ , ‘Banan’ , ‘Orange’ ]
f or item in all_fruits:
if item in my_favorite_fruits:
print (item + ‘ is my favorite fruit’ )
else :
print ( ‘I do not like ‘ + item)
>>> Apple is my favorite fruit
>>> I do not like Grape
>>> I do not like Peach
>>> Banan is my favorite fruit
>>> Orange is my favorite fruit
Методы для работы со списками
Начнем с метода append(), который добавляет элемент в конец списка:
# Создаем список, состоящий из четных чисел от 0 до 8 включительно
numbers = list ( range ( 0 ,10, 2 ))
# Добавляем число 200 в конец списка
numbers. append ( 200 )
numbers. append ( 1 )
numbers. append ( 2 )
numbers. append ( 3 )
print (numbers)
>>> [ 0 , 2 , 4 , 6 , 8 , 200 , 1 , 2 , 3 ]
Мы можем передавать методу append() абсолютно любые значения:
all_types = [ 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. append ( 1024 )
all_types. append ( ‘Hello world!’ )
all_types. append ([ 1 , 2 , 3 ])
print (all_types)
>>> [ 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ], 1024 , ‘Hello world!’ , [ 1 , 2 , 3 ]]
Метод append() отлично выполняет свою функцию. Но, что делать, если нам нужно добавить элемент в середину списка? Это умеет метод insert(). Он добавляет элемент в список на произвольную позицию. insert() принимает в качестве первого аргумента позицию, на которую нужно вставить элемент, а вторым — сам элемент.
# Создадим список чисел от 0 до 9
numbers = list ( range ( 10 ))
# Добавление элемента 999 на позицию с индексом 0
numbers. insert ( 0 , 999 )
print (numbers) # первый print
numbers. insert ( 2 , 1024 )
print (numbers) # второй print
numbers. insert ( 5 , ‘Засланная строка-шпион’ )
print (numbers) # третий print
>>> [ 999 , 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # первый print
>>> [ 999 , 0 , 1024 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # второй print
>>> [ 999 , 0 , 1024 , 1 , 2 , ‘Засланная строка-шпион’ , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # третий print
Отлично! Добавлять элементы в список мы научились, осталось понять, как их из него удалять. Метод pop() удаляет элемент из списка по его индексу:
numbers = list ( range ( 10 ))
print (numbers) # 1
# Удаляем первый элемент
numbers. pop ( 0 )
print (numbers) # 2
numbers. pop ( 0 )
print (numbers) # 3
numbers. pop ( 2 )
print (numbers) # 4
# Чтобы удалить последний элемент, вызовем метод pop без аргументов
numbers. pop ()
print (numbers) # 5
numbers. pop ()
print (numbers) # 6
>>> [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # 1
>>> [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # 2
>>> [ 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ] # 3
>>> [ 2 , 3 , 5 , 6 , 7 , 8 , 9 ] # 4
>>> [ 2 , 3 , 5 , 6 , 7 , 8 ] # 5
>>> [ 2 , 3 , 5 , 6 , 7 ] # 6
Теперь мы знаем, как удалять элемент из списка по его индексу. Но что, если мы не знаем индекса элемента, но знаем его значение? Для такого случая у нас есть метод remove(), который удаляет первый найденный по значению элемент в списке.
all_types = [ 10 , ‘Python’ , 10 , 3.14 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]]
all_types. remove ( 3.14 )
print (all_types) # 1
all_types. remove ( 10 )
print (all_types) # 2
all_types. remove ( ‘Python’ )
print (all_types) # 3
>>> [ 10 , ‘Python’ , 10 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]] # 1
>>> [ ‘Python’ , 10 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]] # 2
>>> [ 10 , ‘Python’ , [ ‘I’ , ‘am’ , ‘list’ ]] # 3
А сейчас немного посчитаем, посчитаем элементы списка с помощью метода count()
numbers = [ 100 , 100 , 100 , 200 , 200 , 500 , 500 , 500 , 500 , 500 , 999 ]
print (numbers. count ( 100 )) # 1
print (numbers. count ( 200 )) # 2
print (numbers. count ( 500 )) # 3
print (numbers. count ( 999 )) # 4
В программировании, как и в жизни, проще работать с упорядоченными данными, в них легче ориентироваться и что-либо искать. Метод sort() сортирует список по возрастанию значений его элементов.
numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. sort ()
print (numbers) # 1
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits) # 2
>>> [ 2 , 3 , 9 , 11 , 78 , 100 , 567 , 1024 ] # 1
>>> [ ‘Apple’ , ‘Banan’ , ‘Grape’ , ‘Orange’ , ‘Peach’ ] # 2
Мы можем изменять порядок сортировки с помощью параметра reverse. По умолчанию этот параметр равен False
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. sort ()
print (fruits) # 1
fruits. sort (reverse = True)
print (fruits) # 2
>>> [ ‘Apple’ , ‘Banan’ , ‘Grape’ , ‘Orange’ , ‘Peach’ ] # 1
>>> [ ‘Peach’ , ‘Orange’ , ‘Grape’ , ‘Banan’ , ‘Apple’ ] # 2
Иногда нам нужно перевернуть список, не спрашивайте меня зачем. Для этого в самом лучшем языке программирования на этой планете JavaScr..Python есть метод reverse():
numbers = [ 100 , 2 , 11 , 9 , 3 , 1024 , 567 , 78 ]
numbers. reverse ()
print (numbers) # 1
fruits = [ ‘Orange’ , ‘Grape’ , ‘Peach’ , ‘Banan’ , ‘Apple’ ]
fruits. reverse ()
print (fruits) # 2
>>> [ 78 , 567 , 1024 , 3 , 9 , 11 , 2 , 100 ] # 1
>>> [ ‘Apple’ , ‘Banan’ , ‘Peach’ , ‘Grape’ , ‘Orange’ ] # 2
Допустим, у нас есть два списка и нам нужно их объединить. Программисты на C++ cразу же кинулись писать циклы for, но мы пишем на python, а в python у списков есть полезный метод extend(). Этот метод вызывается для одного списка, а в качестве аргумента ему передается другой список, extend() записывает в конец первого из них начало второго:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. extend (vegetables)
print (fruits)
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ , ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
В природе существует специальный метод для очистки списка — clear()
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
vegetables = [ ‘Tomato’ , ‘Cucumber’ , ‘Potato’ , ‘Carrot’ ]
fruits. clear ()
vegetables. clear ()
print (fruits)
print (vegetables)
Осталось совсем чуть-чуть всего лишь пара методов, так что делаем последний рывок! Метод index() возвращает индекс элемента. Работает это так: вы передаете в качестве аргумента в index() значение элемента, а метод возвращает его индекс:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
print (fruits. index ( ‘Apple’ ))
print (fruits. index ( ‘Banana’ ))
print (fruits. index ( ‘Grape’ ))
Финишная прямая! Метод copy(), только не падайте, копирует список и возвращает его брата-близнеца. Вообще, копирование списков — это тема достаточно интересная, давайте рассмотрим её по-подробнее.
Во-первых, если мы просто присвоим уже существующий список новой переменной, то на первый взгляд всё выглядит неплохо:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
print (fruits)
print (new_fruits)
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
Но есть одно маленькое «НО»:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits
fruits. pop ()
print (fruits)
print (new_fruits)
# Внезапно, из списка new_fruits исчез последний элемент
>>> [ ‘Banana’ , ‘Apple’ ]
>>> [ ‘Banana’ , ‘Apple’ ]
При прямом присваивании списков копирования не происходит. Обе переменные начинают ссылаться на один и тот же список! То есть если мы изменим один из них, то изменится и другой. Что же тогда делать? Пользоваться методом copy(), конечно:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
new_fruits = fruits. copy ()
fruits. pop ()
print (fruits)
print (new_fruits)
>>> [ ‘Banana’ , ‘Apple’ ]
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ ]
Отлично! Но что если у нас список в списке? Скопируется ли внутренний список с помощью метода copy() — нет:
fruits = [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ , ‘Peach’ ]]
new_fruits = fruits. copy ()
fruits[ -1 ]. pop ()
print (fruits) # 1
print (new_fruits) # 2
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ ]] # 1
>>> [ ‘Banana’ , ‘Apple’ , ‘Grape’ , [ ‘Orange’ ]] # 2
Решение задач
1. Создайте список из 10 четных чисел и выведите его с помощью цикла for
2. Создайте список из 5 элементов. Сделайте срез от второго индекса до четвертого
3. Создайте пустой список и добавьте в него 10 случайных чисел и выведите их. В данной задаче нужно использовать функцию randint.
from random import randint
n = randint ( 1 , 10 ) # Случайное число от 1 до 10
4. Удалите все элементы из списка, созданного в задании 3
5. Создайте список из введенной пользователем строки и удалите из него символы ‘a’, ‘e’, ‘o’
6. Даны два списка, удалите все элементы первого списка из второго
a = [ 1 , 3 , 4 , 5 ]
b = [ 4 , 5 , 6 , 7 ]
# Вывод
>>> [ 6 , 7 ]
7. Создайте список из случайных чисел и найдите наибольший элемент в нем.
8. Найдите наименьший элемент в списке из задания 7
9. Найдите сумму элементов списка из задания 7
10. Найдите среднее арифметическое элементов списка из задания 7
Сложные задачи
1. Создайте список из случайных чисел. Найдите номер его последнего локального максимума (локальный максимум — это элемент, который больше любого из своих соседей).
2. Создайте список из случайных чисел. Найдите максимальное количество его одинаковых элементов.
3. Создайте список из случайных чисел. Найдите второй максимум.
a = [ 1 , 2 , 3 ] # Первый максимум == 3, второй == 2
4. Создайте список из случайных чисел. Найдите количество различных элементов в нем.
Как обратиться к элементу массива python
К элементам в списке мы можем обращаться по-разному. Не только с помощью циклов. Например, если мы знаем порядковый номер элемента в списке, то есть его индекс, то можем по нему обратиться к элементу. Например, мы знаем, что в нашем my_list = [1, 1.4, ‘line’, [1, 2, 3], 1.4] элемент «line» третий по счету, но если считать по-питоновски, то есть от 0, то получается, что второй. То есть индекс элемента «line» — 2. Поэтому обратиться к этому элементу мы можем вот так — my_list[2] — сначала название списка, а затем в квадратных скобках нужно указать индекс.
Но когда элементов в списке очень много и просто глазами определить индекс каждого элемента не получается, можно узнать его с помощью команды .index(). Сначала нужно указать название списка, потому команду, а в скобках сам элемент, индекс которого вы хотите определить, — my_list.index(1.4). В ответ мы получим 1.
Только учтите, если у вас есть несколько одинаковых элементов в списке, то это команда вернет вам индекс того, что стоит первым в списке.
Пока что я вручную создавала списки и добавляла в них элементы, но так во взрослой жизни не делается. Для того, чтобы добавить элемент в список используется специальная команда .append(). И указанный в скобках элемент добавляется в конец списка.
Команда .insert() тоже добавляет элементы в список, но в определенное место. Первым параметром вы вводите индекс, по которому нужно разместить элемент, а вторым параметром — сам элемент. В output можно увидеть, что элемент встраивается в список ровно на то место, которое мы указали, а все остальные элементы смещаются вправо от него.
Также есть и специальная команда для удаления элементов из списка — .remove(), где в скобочках нужно указать, какой именно элемент должен быть удален из списка. Но если таких элементов в списке несколько, удалится только самый первый. Если вы попросите удалить элемент, которого нет в списке, то вы получите ошибку. Давайте удалим элемент 100 из списка.
Также списки можно сортировать с помощью функции sorted(). Давайте создадим новый список в числами number_list = [3, 49, 1, 16]. И применим к нему sorted(). Мы увидим, в output отсортированный от меньшего к большему список.
Здесь важно понимать, что после применения sorted() исходный number_list на самом деле никак не изменило. Для того, чтобы сохранить список в отсортированном виде, нужно сохранить sorted(number_list) в переменную.
Сортировать можно, кстати, не только числа в списках, но и строки.
Давайте теперь попрактикуемся и попробуем написать небольшую программу. Она будет 5 раз просить пользователя ввести число и каждое из этих чисел добавлять в список. А потом распечатает нам список из этих 5 чисел. Если вы знаете, как решить эту задачку, то попробуйте сначала сами написать код, а потом сверьтесь с моей версией.
Для начала нужно создать пустой список, куда будут собираться числа, которые ввел пользователь. А дальше с помощью цикла for i in range(5) мы обозначим, что хотим пять раз совершить какую-то операцию. Для начала пять раз с помощью input(«Введите число») попросим пользователя ввести число. А затем введенное число сохраним в наш список. И распечатаем наш список.
Теперь давайте усложним задачу. Теперь программа должна просить пользователя 5 раз ввести четное число, проверять, действительно ли оно четное. Если да, то добавлять в список, если нет, то выводить пользователю на экране *введенное пользователем число* не делится на 2 без остатка.
Для того, чтобы проверять четное число или нет можно использовать деление через %, которое возвращает остаток от деления. Если вы напишете 4%2, то в output будет 0, потому что остатка нет.
Или еще пример. Иногда бывает так, что у вас есть какие-то данные, но в них есть грязь, которую лучше бы вычистить прежде чем приступать к анализу. Например, у нас есть вот такой список — my_list = [‘2%’, «45 %», ‘6%’, “11”, ‘15 %’] . Давайте очистим каждый элемент от лишнего знака %.
Я думаю, вы уже поняли, почему в самом начале урока я сказала, что мы очень часто сталкиваемся со списками по работе. Потому что такой список, это не что иное как просто строчка в таблице. А таблица — это просто список списков. Давайте разберем на другом очень жизненном примере.
Допустим у вас есть данные о количестве преступников в каких-то населенных пунктах — crimes = [30000, 10000, 200]. И мы хотим узнать, в каком из этих населенных пунктах самая криминогенная обстановка. И вы мне скажете: «Так давай используем функцию max(crimes) и она вернет нам это самое большое значение из списка crimes и мы разойдемся.» Технически это будет правильный ответ. Но не все так просто. Показатели типа количества преступников, детей сирот, людей с алкогольной зависимость и так далее обязательно нужно нормировать на количество всех людей проживающих в этом населенном пункте. Иначе всегда бы оказывалось, что Москва самый опасный город в России просто потому, что в Москве живет больше всего людей. Поэтому нам пригодится еще одна строчка в таблице, то есть еще один список — population = [100000, 50000, 1000]. И дальше нам нужно будет по формуле количество преступников/население * 1000 рассчитать число преступников на 1000 человек.
Давайте создадим пустой список norm_crimes = [], в который будем собирать нормированный показатель.
В итоге если мы объединим все три списка в один, то по сути получим обычную таблицу.
Если бы мы сохранили этот наш список списков в xls или csv и открыли бы этот файл в табличном редакторе, то он выглядел бы как обычная таблица.
Можем еще добить нашу табличку, посчитав сумму всех преступников, сумму населения для всех населенных пунктов и общий нормированный показатель для всех населенных пунктов. Чтобы узнать сумму всех чисел в списке, нам не нужно ходить циклом по списку и прибавлять один элемент за другим. Можно использовать sum().
И с помощью команды .append() давайте добавим эти показатели в соответсвующие им списки.
Теперь полученные данные мы могли бы использовать для материала или дальнейшего анализа!)
В этом уроке я рассказала об основных методах и функциях списков, но не обо всех. Как и для чего применяются другие функции можете посмотреть вот здесь. Тетрадку Jupyter Notebook с этим уроком можно найти в нашем GitHub здесь. А если хотите порешать задачки для тренировки, то мы собрали их здесь.
Массивы в Python
В Python нет встроенного типа «массив», но вместо него можно использовать встроенный тип «список» (list). Также при использовании библиотеки NumPy можно создавать объект типа «массив» (Ndarray). Далее о каждом из этих двух вариантов подробнее.
Списки (list)
Список представляет собой тип, который может хранить любое количество элементов разных типов. Создать список в Python можно несколькими способами:
Создание
- Создание пустого списка:
- Создание списка с элементами:
- Создание списка на основе другого списка:
- Создание списка повторением какого-либо элемента или другого списка:
- Создание списка с помощью конструкции range():
Функция range(10) возвращает числа от 0 до 9, на основе которых создаётся новый список.
Обращение к элементу
Обращение к элементу списка производится по индексу элемента:
Индексы элементов начинаются с нулевого, то есть первый элемент списка имеет индекс «0», а второй — «1».
Обход элементов
Элементы списка можно обходить циклами for и while:
Сравнение
Списки можно сравнивать между собой. Для того, чтобы два списка считались равными, они должны иметь одинаковый состав. К примеру, следующие два списка будут равны, не смотря на разные способы их создания:
Размерность
Список в Python может быть как одномерным, так и многомерным. Выше были приведены примеры одномерных списков. Чтобы список был многомерным, например, двухмерным, каждый элемент списка должен представлять собой другой список:
В данном примере список состоит из трёх списков, каждый из которых содержит имя и возраст. Аналогично можно создавать списки с большим количеством измерений — с большим количеством уровней вложенности.
Для получения элемента многомерного списка, нужно указывать столько индексов, сколько измерений необходимо использовать для описания элемента:
Преобразование
Двумерный список можно преобразовать в словарь с парами «ключ-значение»:
Матрицы
Двумерный список является матрицей, которую визуально можно представить в следующем виде:

В данном примере переменная А содержит двумерный список, т.е. список списков, каждый из которых состоит из трёх элементов. Тип list в Python не поддерживает работу со списками как с матрицами, но, тем не менее, позволяет матрицы хранить.
Массивы NumPy (Ndarray)
Создание
Для использования класса Ndarray предварительно необходимо импортировать библиотеку numpy:
Для создания массива используется функция модуля numpy — array():
В первый параметр функции array() передаётся список, поэтому способов создания столько же, сколько способов создания списков. При передаче в параметр многомерного списка будет создан многомерный массив:
Тип значения элементов
В данном примере элементы массива были приведены к строковому типу, так как каждый список главного списка содержал строковое значение. Тип значения элементов массива можно переопределять при создании массива, указывая его вторым параметром функции array():
Обращение к элементам
Обращение к элементам массива Ndarray производится аналогично получение элемента в многомерном списке.
Атрибуты класса Ndarray
Далее рассмотрим атрибуты класса Ndarray:
- ndim — число измерений (осей) массива;
- shape — размерность массива. Это tuple, содержащий натуральные числа (n, m) — длины массива по каждой оси (n — высота, m — ширина). Число элементов кортежа shape равно ndim.
- size — количество элементов в массиве, равно произведению всех элементов атрибута shape;
- dtype — тип элементов массива. NumPy предоставляет возможность использовать как встроенные типы, например: bool_, character, int8, int16, int32, int64, float8, float16, float32, float64, complex64, object_, так и собственные типы данных, в том числе и составные;
- itemsize — размер каждого элемента массива в байтах;
- data — буфер, содержащий фактические элементы массива. Обычно не нужно использовать этот атрибут, так как обращаться к элементам массива проще всего с помощью индексов.
Изменение размерности
Размерность массива darray в Python можно изменять методом reshape():
При этом количество элементов должно позволять это сделать, т.е. произведение элементов атрибута shape до и после изменения размера должно быть одинаковым. К примеру, нельзя изменить размерность массива с (3, 4) на (2, 5), но можно изменить её на (2, 6).