how to use list() in python
时间: 2024-05-08 17:16:53 浏览: 92
详解python中list的使用
The list() function in Python is used to convert an iterable (such as a tuple, set, or string) into a list. Here's an example:
```python
# Create a tuple
my_tuple = (1, 2, 3)
# Convert the tuple into a list
my_list = list(my_tuple)
# Print the list
print(my_list)
```
Output:
```
[1, 2, 3]
```
In this example, we create a tuple called `my_tuple` containing the values 1, 2, and 3. We then use the `list()` function to convert `my_tuple` into a list called `my_list`, which we then print to the console.
You can also use the `list()` function to convert a string into a list of its individual characters:
```python
# Convert a string into a list of characters
my_string = "Hello, world!"
char_list = list(my_string)
# Print the list of characters
print(char_list)
```
Output:
```
['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!']
```
In this example, we create a string called `my_string` containing the phrase "Hello, world!" We then use the `list()` function to convert `my_string` into a list of its individual characters, which we then print to the console.
阅读全文