Python函数返回列表
时间: 2024-06-18 14:02:01 浏览: 276
在Python中,函数可以返回一个列表,这是非常常见的功能,用于将计算结果封装成可操作的数据结构。当你编写一个函数,它执行一些操作并生成一系列相关的值时,你可以通过`return`关键字将这些值放入一个列表中返回给调用者。
例如,假设你有一个函数,用于计算阶乘:
```python
def factorial(n):
result = [i * n for i in range(1, n+1)]
return result
# 使用函数并打印结果
print(factorial(5)) # 输出: [1, 2, 6, 24, 120]
```
在这个例子中,`factorial`函数计算从1到n的所有整数的乘积,并将结果作为一个列表返回。调用这个函数会得到一个包含阶乘值的列表。
阅读全文
相关推荐















