collections list
时间: 2023-11-07 08:48:08 浏览: 78
Collections in Python are containers that are used to store and organize data. One commonly used collection type is a list. A list is an ordered collection of elements enclosed in square brackets ([]), and the elements can be of different types (e.g., numbers, strings, or even other lists). Lists have several built-in methods that allow you to manipulate and access their elements.
Here's an example of creating a list and performing some common operations on it:
```python
# Creating a list
my_list = [1, 2, 3, 4, 5]
# Accessing elements
print(my_list[0]) # Output: 1
# Modifying elements
my_list[2] = 10
# Adding elements
my_list.append(6)
# Removing elements
my_list.remove(3)
# Length of the list
print(len(my_list)) # Output: 5
# Looping through the list
for element in my_list:
print(element)
# Sorting the list
my_list.sort()
# Reversing the list
my_list.reverse()
```
These are just a few examples of what you can do with lists. Python provides many more methods and functionalities for lists and other collections. Let me know if you have any specific questions or need further information!
阅读全文