# 6.列表

* 列表是Python中的基本数据结构，是可以修改的。
* 列表可以通过索引访问元素，正向索引从 0 开始，反向索引从 -1 开始；
* 列表都可以进行的操作包括索引，切片，加，乘，检查成员。
* 列表内置了许多常用的方法，包括获取列表长度，列表最大最小的元素，
* 列表中的元素可以是不同的类型

## 1. 访问列表中的元素

列表中的元素通过索引访问，正向索引从 0 开始，反向索引从 -1 开始

![](https://pic.existorlive.cn/%E6%88%AA%E5%B1%8F2021-11-22%20%E4%B8%8A%E5%8D%8812.27.53.png)

![](https://pic.existorlive.cn/%E6%88%AA%E5%B1%8F2021-11-22%20%E4%B8%8A%E5%8D%8812.28.10.png)

```python
ls = [1,2,3,4]
print(ls[0])   # 1
print(ls[-1])  # 4
```

## 2. 列表切片

```python
ls = [1,2,3,4]

print(ls[0:-1])   # [1,2,3]

```

![](https://pic.existorlive.cn/%E6%88%AA%E5%B1%8F2021-11-22%20%E4%B8%8A%E5%8D%8812.32.01.png)

## 3. 修改列表

```python
ls = [1,2,3,4]

# 通过索引修改元素
ls[0] = 11 
print(ls)      # [11,2,3,4] 

# 在列表后插入元素 
ls.append(13)
print(ls)      # [11,2,3,4,13]

# 删除元素
del ls[0]
print(ls)      # [2,3,4,13]

# 在头部插入元素 
ls.insert(0,15)
print(ls)      # [15,2,3,4,13]

```

## 4. 遍历

```python
ls = [1,2,3,4]

for item in ls:
    print(item)

```

## 4. 常用方法

```swift

len(list)     # 列表长度

max(list)     # 最大值

min(list)     # 最小值

list(tuple)   # 将元组转换为列表


# 在列表末尾添加新的对象
list.append(obj)

# 统计某个元素在列表中出现的次数
list.count(obj)

# 在列表末添加另一个列表的元素
list.extend(list1)

# 插入元素
list.insert(index,obj)

# 移除某个元素
list.remove(obj)

# 移除索引指定的一个元素（默认最后一个元素），并且返回该元素的值
list.pop(index=-1)

# 反序
list.reverse()

# 排序
list.sort(key=None,reverse=False)

# 清空列表
list.clear()

# 复制列表
list.copy()
```


---

# Agent Instructions: 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://gitbook.existorlive.cn/kai-fa-yu-yan-xue-xi/python/6.-lie-biao.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.
