how to create a python list
To create a Python list, you can follow these steps:
- Declare an empty list using square brackets:
my_list = []
- Initialize the list with elements:
my_list = [1, 2, 3]
- You can also create a list with different data types:
my_list = [1, 'Hello', 3.14, True]
- Use the
list()constructor:
my_list = list()
- Add elements to the list using the
append()method:
my_list.append(1)
my_list.append('Hello')
my_list.append(3.14)
- Access elements of the list by their index:
print(my_list[0]) # Output: 1
print(my_list[1]) # Output: 'Hello'
- Modify elements of the list:
my_list[0] = 10
- Get the length of the list using the
len()function:
print(len(my_list)) # Output: 3
- Remove elements from the list using the
remove()method:
my_list.remove('Hello')
- Iterate over the elements of the list:
for item in my_list:
print(item)
These are the basic operations to create a Python list. Feel free to explore more methods and functionalities available for lists in Python
原文地址: https://www.cveoy.top/t/topic/iNHB 著作权归作者所有。请勿转载和采集!