Built-in collection data types Flashcards

1
Q

Объявление list

A

names = [“John”, “Peter”, “Debora”, “Charles”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Получение значения из list или tuple с помощью индекса

A

furniture = [“table”, “chair”, “rack”, “shelf”]
furniture[0] # table
furniture[-1] # shelf

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Получение значения из list или tuple с помощью slices

A

В slices лучше воспринимать значения как указание порядкового номера разделителя - запятой. Начинаются с 0.

furniture = [“table”, “chair”, “rack”, “shelf”]
furniture[0:3] # table, chair, rack
furniture[1:3] # chair, rack
furniture[0:-1] # table, chair, rack
furniture[:2] # table, chair
furniture[2:] #rack, shelf
furniture[:] # все значения, создается копия

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Получение длинны list или tupe

A

len(furniture)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Изменение значения в list

A

furniture[0] = “desk”
furniture[2] = furniture[1]
furniture[-1] = “bed”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Concatenation and Replication

A

[1, 2, 3] + [“A”, “B”, “C”] # [1, 2, 3, “A”, “B”, “C”]
[“X”, “Y”, “Z”] * 3 # [“X”, “Y”, “Z”, “X”, “Y”, “Z”, “X”, “Y”, “Z”]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Получение индекса в цикле

A

for index, item in enumerate(furniture):
print(f”: {index} - item: {item}”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Цикл по нескольким list или tuple сразу

A

furniture = [‘table’, ‘chair’, ‘rack’, ‘shelf’]
price = [100, 50, 80, 40]

for item, amount in zip(furniture, price):
print(f’The {item} costs ${amount}’)

Если длина разная, то остановка идет на самом коротком.
Возвращаемый тип zip. Можно перевести к list: list(<zip>)</zip>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Как проверить входит или не входит элемент в list или tupe

A

“bed” in furniture
“rack” not in furniture

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Множественное присваивание

A

furniture = [‘table’, ‘chair’, ‘rack’, ‘shelf’]
table, chair, rack, shelf = furniture

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Swap

A

a, b = b, a

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Получение индекса элемента

A

furniture = [‘table’, ‘chair’, ‘rack’, ‘shelf’]
furniture.index(‘chair’) # 1

Если элемента нет, то будет exception c ValueError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Добавление значения в конец list

A

furniture.append(“bed”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Вставка элемента в нужную позицию в list

A

furniture.insert(1, “bed”)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Удаление элемента из list с помощью индекса

A

del furniture[2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Удаление элемента из list с помощью названия

A

furniture.remove(“chair”)

17
Q

Вернуть элемент из list и сразу удалить его из него. Чаще всего используется для последнего

A

animals = [“cat”, “bat”, “rat”, “elephant”]

animals.pop() # elephant
animals.pop(0) # cat

18
Q

Сортировка list

A

Изменяют текущий list
furniture.sort()
furniture.sort(reverse=True)

Возвращает новый list
sorted(furniture)

19
Q

Сортировка значений в алфавитном порядке в list

A

letters.sort(key=str.lower)

20
Q

Объявление tuple

A

furniture = (“table”, “chair”, “rack”, “shelf”)

21
Q
A