Python list()函数
时间: 2024-03-28 20:15:21 浏览: 23
`list()` 函数是 Python 内置函数之一。它可以将可迭代对象(如元组、字符串、字典、集合等)转换为列表。
语法如下:
```python
list(iterable)
```
其中,`iterable` 是可迭代对象。执行该函数后,会返回一个新的列表对象。
示例:
```python
# 将元组转换为列表
tup = (1, 2, 3)
lst = list(tup)
print(lst) # [1, 2, 3]
# 将字符串转换为列表
str1 = "hello"
lst1 = list(str1)
print(lst1) # ['h', 'e', 'l', 'l', 'o']
# 将集合转换为列表
set1 = {4, 5, 6}
lst2 = list(set1)
print(lst2) # [4, 5, 6]
```
需要注意的是,如果 `iterable` 已经是列表对象,那么 `list()` 函数会返回该对象本身,而不是新的列表对象。
相关问题
python list函数
Python的list函数是一个内置函数,它可以用来创建一个包含任意数量元素的列表。该函数的语法如下:
```
list(iterable)
```
其中,iterable是一个可迭代对象,如字符串、元组、列表等。list函数将可迭代对象转换为一个新的列表对象,并返回该列表。
例如,以下代码演示了如何使用list函数创建一个包含三个元素的列表:
```
my_list = list([1, 2, 3])
print(my_list) # 输出 [1, 2, 3]
```
需要注意的是,list函数也可以用于将其他类型的对象转换为列表,例如将字符串转换为列表:
```
my_list = list('hello')
print(my_list) # 输出 ['h', 'e', 'l', 'l', 'o']
```
python list 函数
Python 中的 list 函数主要是用于将可迭代对象转换为列表。该函数接受一个可迭代对象作为参数,例如字符串、元组、集合等,然后将其转换为一个列表返回。例如:
```python
>>> s = 'hello'
>>> l = list(s)
>>> print(l)
['h', 'e', 'l', 'l', 'o']
```
除了将可迭代对象转换为列表之外,list 函数还支持两种常见的用法:
1. 创建一个空列表
```python
>>> l = list()
>>> print(l)
[]
```
2. 将一个可变长度的参数列表转换为列表
```python
>>> l = list(1, 2, 3, 4)
>>> print(l)
[1, 2, 3, 4]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)