How do you insert an element into a list in Python?
To add elements to the middle of a list, you can use the insert() method. The first parameter of this method is the index of the position to insert, while the second parameter is the element to be inserted.
Here is an example:
my_list = [1, 2, 3, 4]
my_list.insert(2, 5) # 在位置索引2处插入元素5
print(my_list) # 输出 [1, 2, 5, 3, 4]
In the example above, we insert element 5 at position index 2, which is inserting the element in the middle of the list. Ultimately, the list becomes [1, 2, 5, 3, 4].