# 17.4.4 list类型

* 列表的元素类型为string
* 按照插⼊顺序排序

## 增加

* 在左侧插⼊数据

  ```
  lpush key value1 value2 ...
  ```
* 在右侧插⼊数据

  ```
  rpush key value1 value2 ...
  ```
* 在指定元素的前或后插⼊新元素

  ```
  linsert key before或after 现有元素 新元素
  ```

## 获取

* 返回列表⾥指定范围内的元素
* start、stop为元素的下标索引
* 索引从左侧开始，第⼀个元素为0
* 索引可以是负数，表示从尾部开始计数，如-1表示最后⼀个元素

  ```
  lrange key start stop
  ```

设置指定索引位置的元素值

索引从左侧开始，第⼀个元素为0

* 索引可以是负数，表示尾部开始计数，如-1表示最后⼀个元素

lset key index value

* 例5：修改键为'a1'的列表中下标为1的元素值为'z'

lset a1 1 z

![Image](https://github.com/clay-wangzhi/wiki/tree/46b947765d64b8562206df9ac2bae98e26b90b86/17%20Redis/17.4%20数据库操作/images/2d0e9776c8d627c94d31dda913cdee8690173dff.png)

删除

* 删除指定元素
* 将列表中前count次出现的值为value的元素移除
* count > 0: 从头往尾移除
* count < 0: 从尾往头移除
* count = 0: 移除所有

lrem key count value

* 例6.1：向列表'a2'中加⼊元素'a'、'b'、'a'、'b'、'a'、'b'

lpush a2 a b a b a b

![Image](https://github.com/clay-wangzhi/wiki/tree/46b947765d64b8562206df9ac2bae98e26b90b86/17%20Redis/17.4%20数据库操作/images/502fb1c7f71408b5df0098c5ea3cde1263bbbe94.png)

例6.2：从'a2'列表右侧开始删除2个'b'

lrem a2 -2 b

* 例6.3：查看列表'py12'的所有元素

lrange a2 0 -1

![Image](https://github.com/clay-wangzhi/wiki/tree/46b947765d64b8562206df9ac2bae98e26b90b86/17%20Redis/17.4%20数据库操作/images/512611397a7c8691dade0417ac834e0c81b82ea2.png)


---

# 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://wiki.clay-wangzhi.com/17-redis/17.4-shu-ju-ku-cao-zuo/17.4.4-list-lei-xing.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.
