How to add elements in Python?
In Python, you can use the append() method to add elements to a list, use the insert() method to insert elements at a specific position, and use the extend() method to add the elements of one list to another list.
Here is an example code:
- add()
my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list) # 输出:[1, 2, 3, 4, 5]
- add in
my_list = [1, 2, 3, 4]
my_list.insert(2, 5)
print(my_list) # 输出:[1, 2, 5, 3, 4]
- prolong()
my_list = [1, 2, 3, 4]
another_list = [5, 6, 7]
my_list.extend(another_list)
print(my_list) # 输出:[1, 2, 3, 4, 5, 6, 7]
Note: The above method operates directly on the original list when making modifications and does not return a new list.