How can elements be added to an empty list created in Python?
In Python, you can create an empty list and add elements to it using the following method:
- Create an empty list using empty square brackets [] and add elements to the list using the append() method. For example:
my_list = []
my_list.append(1)
my_list.append(2)
print(my_list) # 输出 [1, 2]
- Create an empty list using list comprehension and add elements to the list through a loop. For example:
my_list = [x for x in range(5)]
print(my_list) # 输出 [0, 1, 2, 3, 4]
- Create an empty list using a list comprehension and add elements to the list using the extend() method. For example:
my_list = list(range(3))
my_list.extend([3, 4])
print(my_list) # 输出 [0, 1, 2, 3, 4]
No matter which method is used, it is possible to create an empty list and add elements to it.