深度阅读

How to to remove an element from an array or list

作者
作者
2023年08月22日
更新时间
6.98 分钟
阅读时间
0
阅读量

In Python, you can use the remove() function or the pop() function to remove an element from an array or list.

The remove() function can be used to remove a specific element, as shown below:

my_list = [1, 2, 3, 4]
my_list.remove(2) # remove element 2
print(my_list) # [1, 3, 4]

The pop() function can be used to remove an element by its index in the list, as shown below:

my_list = [1, 2, 3, 4]
my_list.pop(2) # remove element at index 2 (i.e., 3)
print(my_list) # [1, 2, 4]

If you don’t specify an index for pop(), it will remove the last element from the list by default.

Please note that these functions modify the original list, so use them with caution.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。