> For the complete documentation index, see [llms.txt](https://kaze.gitbook.io/qa-theory/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/spiski-i-ikh-metody.md).

# Списки и их методы

### **1. Что такое список**

* Список — это **изменяемая (mutable) последовательность объектов**.
* Создаётся с помощью квадратных скобок `[]` или функции `list()`.

```python
lst1 = [1, 2, 3]
lst2 = list([4, 5, 6])
lst3 = []  # пустой список
```

***

### **2. Основные методы списков**

| Метод                           | Описание                                                        | Пример              |
| ------------------------------- | --------------------------------------------------------------- | ------------------- |
| `append(x)`                     | Добавляет элемент в конец                                       | `lst.append(4)`     |
| `extend(iterable)`              | Добавляет все элементы из другого итерируемого объекта          | `lst.extend([5,6])` |
| `insert(i, x)`                  | Вставляет элемент на позицию i                                  | `lst.insert(1, 10)` |
| `remove(x)`                     | Удаляет первое вхождение элемента                               | `lst.remove(2)`     |
| `pop([i])`                      | Удаляет и возвращает элемент по индексу, по умолчанию последний | `lst.pop()`         |
| `clear()`                       | Очищает список                                                  | `lst.clear()`       |
| `index(x, [start, end])`        | Индекс первого вхождения элемента                               | `lst.index(3)`      |
| `count(x)`                      | Количество вхождений элемента                                   | `lst.count(2)`      |
| `sort(key=None, reverse=False)` | Сортирует список на месте                                       | `lst.sort()`        |
| `reverse()`                     | Разворачивает список на месте                                   | `lst.reverse()`     |
| `copy()`                        | Поверхностная копия списка                                      | `lst2 = lst.copy()` |

***

### **3. Особенности списков**

1. **Изменяемость**
   * Можно менять элементы, добавлять, удалять:

```python
lst = [1, 2, 3]
lst[0] = 10  # [10, 2, 3]
```

2. **Поддержка индексации и срезов**

```python
lst = [1, 2, 3, 4]
print(lst[1:3])  # [2, 3]
print(lst[-1])   # 4
```

3. **Могут содержать любые типы данных**

```python
lst = [1, "text", [2,3], (4,5)]
```

4. **Поддержка операций последовательностей**

* Конкатенация (`+`), повторение (`*`), проверка элемента (`in`), `len()`

```python
lst1 = [1,2]
lst2 = [3,4]
print(lst1 + lst2)  # [1,2,3,4]
print(lst1 * 2)     # [1,2,1,2]
```

***

### **4. Применение в автотестах**

* **Хранение и проверка данных из API**

```python
users = ["Alice", "Bob", "Carol"]
assert "Bob" in users
```

* **Модификация тестовых данных**

```python
data = [1,2,3]
data.append(4)
assert data == [1,2,3,4]
```

* **Сортировка и фильтрация**

```python
scores = [10, 5, 7]
scores.sort()
assert scores == [5,7,10]
```

* **Использование с генераторами данных**

```python
squares = [x*x for x in range(5)]
assert squares == [0,1,4,9,16]
```

***

💡 **Вывод:**

* Списки — **изменяемые последовательности**, поддерживают индексацию, срезы, множество методов для добавления, удаления, сортировки и копирования элементов.
* Идеальны для **хранения и обработки коллекций данных** в автотестах.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kaze.gitbook.io/qa-theory/osnovy-programmirovaniya-na-python/spiski-i-ikh-metody.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
