跳至主要内容

如何使用 Python 的 pop() 方法

学习如何使用 Python 的 pop() 方法从列表和字典中移除元素,包括在迭代时如何移除项。了解如何避免诸如 IndexError 和 KeyError 之类的常见错误。
· 9分钟 阅读

使用 AI 探索

pop() 方法是 Python 中用于数据处理的重要函数,可从列表或字典中移除并返回指定元素。Python 程序员偏爱使用 pop() 方法,因为它是修改列表和字典等数据结构的一种格外简便的方式。

在进一步展开之前,我强烈建议您先学习 DataCamp 的 Introduction to Python 课程,掌握 Python 语言基础。Python Cheat Sheet for Beginners 也有助于您查阅并理解 Python 的语法和不同函数。

快速解答:如何在 Python 中使用 pop() 方法

pop() 方法在列表和字典中用于移除指定项并返回其值。我将分别给出一个快速示例。第一个示例展示如何用 pop() 方法从列表中移除一项。以下代码将打印 5。

# Create a list
my_list = [1, 2, 3, 4, 5]

# Removes and returns the last element of the list
last_element = my_list.pop()
print(last_element)

下一个示例展示如何使用 pop() 方法从字典中移除特定键。以下代码将打印 3。

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Removes and returns the value associated with the key 'b'
value = my_dict.pop('c')
print(value)

在列表中使用 pop()

pop() 方法用于列表时,会从该列表中移除并返回指定元素。下面展示了在列表中使用 pop() 方法的语法。

list.pop([index])

在列表中使用 pop() 方法时,它可以接收一个可选参数来指定要移除的索引。如果未提供参数,pop() 方法将移除并返回列表中的最后一个元素。

如果您选择显式指定索引,请注意如果指定不正确且超出范围,将会引发 IndexError。下面我们来看看 pop() 方法在列表中的不同用例。

使用 pop() 按索引移除元素

您也可以在 pop() 方法中使用正索引或负索引作为参数,指定要从列表中移除的元素。在 Python 中,正索引从列表开头的 0 开始;负索引从列表末尾的 -1 开始计数。

以下示例展示了三种从列表中移除元素的方法。在每种情况下,代码输出都会打印 5。

# Create a list
my_list = [1, 2, 3, 4, 5]

# Removes and returns the last element of the list
last_element = my_list.pop()
print(last_element)
# Create a list
my_list = [1, 2, 3, 4, 5]

# Remove specific element using negative index
removed_element = my_list.pop(-1) 
print(removed_element)  
# Create  a list
my_list = [1, 2, 3, 4, 5]

# Remove specific element using negative index
removed_element = my_list.pop(4) 
print(removed_element) 

在迭代时使用 pop() 从列表移除项

您可以在循环中使用 pop() 方法遍历列表,每次都移除最后一个元素,直到列表为空。下面的示例展示了如何在循环中使用 pop() 方法。代码将打印 List is now empty。

# Create a list
my_list = [1, 2, 3, 4, 5]

# Create a function to remove items from the list
while my_list:
    element = my_list.pop()
    print(f"Removed element: {element}")
print("List is now empty:", my_list)

这种技巧在多种场景中很有用。比如,您有一个待办任务列表需要逐一处理。通过使用 pop(),您可以在完成每个任务后将其移除,让列表始终聚焦于剩余事项。

在嵌套列表中使用 pop()

您可以使用 pop() 方法从嵌套列表中移除元素。该方法会移除并返回嵌套列表中指定的列表。以下代码将打印 [7, 8, 9]。

# Define a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Pop an element from the outer list
removed_list = nested_list.pop()
print(removed_list)

如果您想从内层列表中移除特定元素,需要先在嵌套列表中指定该列表的索引。下面的代码打印 9,它是索引为 2 的列表中的最后一个元素。

# Define a nested list
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

# Pop an element from an inner list
removed_element = nested_list[2].pop()
print(removed_element)

处理 pop() 索引越界

当您尝试用超出该列表范围的索引来移除元素时,会引发 IndexError。为避免此错误,重要的是先检查列表长度,再提供合适的索引。您也可以使用 try-except 代码块来捕获错误。下面两段代码都会打印 Index out of range。

# Create a list
my_list = [1, 2, 3]

# Check length before popping
index = 4

# Ensure the index is within the valid range of the list
if 0 <= index < len(my_list):
    # Removes and returns the element at the specified index
    element = my_list.pop(index)  
    print(f"Popped element: {element}")
else:
    print("Index out of range")
# Create a list
my_list = [1, 2, 3]

# Using try-except block to handle out-of-range index
try:
    # Attempt to remove and return the element at index 5
    element = my_list.pop(5)
except IndexError:
    # Catches the IndexError if the index is out of range
    print("Index out of range")

在字典中使用 pop()

pop() 方法用于字典时,会移除指定键并返回其值。下面展示了在字典中使用 pop() 方法的语法。

dict.pop(key[, default])

可以看到,在字典中使用 pop() 方法时,需要将键作为参数传入。 pop() 方法会返回指定键所对应的值,并从字典中移除该键值对。

您也可以提供一个可选的默认值,以便在找不到该键时返回。如果指定的键不存在且未提供默认值,将引发 KeyError;如果提供了默认值,则返回该默认值。

Python 字典默认值

在字典中使用 pop() 方法时,您可以提供默认值用于在找不到键时返回。该方法通常用于防止 KeyError。由于键 d 不在集合中,下面的代码将打印 Not Found。

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Remove a specific key and provide default value
value = my_dict.pop('d', 'Not Found')

# Prints the returned value
print(value)

在嵌套字典中使用 pop() 方法

与列表类似,您可以使用 pop() 方法移除嵌套字典中的元素。嵌套字典是指字典中的字典。以下代码将打印 {'x': 7, 'y': 8, 'z': 9}。

# Define a nested dictionary
nested_dict = {
    'a': {'x': 1, 'y': 2, 'z': 3},
    'b': {'x': 4, 'y': 5, 'z': 6},
    'c': {'x': 7, 'y': 8, 'z': 9}
}

# Pop a key-value pair from the outer dictionary
removed_dict = nested_dict.pop('c')
print(removed_dict)

您也可以通过指定键,从嵌套字典中的特定字典里移除内层的值。下面的代码将打印 2。

# Define a nested dictionary
nested_dict = {
    'a': {'x': 1, 'y': 2, 'z': 3},
    'b': {'x': 4, 'y': 5, 'z': 6},
    'c': {'x': 7, 'y': 8, 'z': 9}
}

# Pop a key-value pair from an inner dictionary
popped_inner_value = nested_dict['a'].pop('y')
print(popped_inner_value)

处理字典中的 KeyError

另一种更为优雅地处理 KeyError 的常见方法是使用 try-except 代码块来捕获错误。 以下示例演示了如何将 try-except 技巧与 pop() 方法结合使用。

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Create the try-except block to catch the error
try:
    value = my_dict.pop('d')
except KeyError:
    print("Key not found")

您还可以使用 in 关键字,在移除前检查字典中是否存在某个特定键。下面的代码使用该方法并返回 Key not found.

# Create a dictionary
my_dict = {'a': 1, 'b': 2}

# Check key existence before popping
key = 'c'
if key in my_dict:
    value = my_dict.pop(key)
    print(f"Popped value: {value}")
else:
    print("Key not found.")

性能考量

本节我们将看看在列表和字典中使用 pop() 方法的性能影响。

列表操作

pop() 在列表中的时间复杂度取决于被移除元素的索引位置。当不传参数或使用 -1 作为索引来移除最后一个元素时,操作为 O(1),因为它只移除列表的最后一个元素,不会改变其他元素。

当我们使用 pop() 方法移除第一个或任意其他位置的元素时,时间复杂度为 O(n),因为这涉及移除一个元素并将其后的元素重新移动到新的索引位置。想进一步了解 Python 中的时间复杂度,请查看我们的 Analyzing Complexity of Code through Python 教程。

字典操作

由于底层哈希表的实现,字典中的 pop() 方法效率很高。在这种情况下,字典的 pop() 方法通常是 O(1) 操作。

这种时间复杂度的原因在于字典将键存储在哈希表中,插入、删除和查找都需要一定时间。另外请注意,在字典中使用 pop() 方法时,您必须始终指定要移除的键。想了解更多有关哈希表的内容,请查看我们的 A Guide to Python Hashmaps 教程以了解更多哈希表相关知识。

Python 的 pop() 方法替代方案

尽管 pop() 方法在从列表和字典中移除元素时非常有效,但也有一些替代方法。

使用 del 关键字

del 关键字用于通过指定元素索引来从列表中移除一项。del 也可用于从字典中移除指定的键值对。需要注意的是,与 pop() 方法不同,使用 del 不会返回被移除的元素。

下面的示例展示了如何使用 del 关键字从列表和字典中移除元素。在移除索引为 2 的元素后,以下代码将打印新列表 [1, 2, 4, 5]。

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Remove item at index 2
del my_list[2]
print(my_list)

以下代码将打印 {'a': 1, 'c': 3}。

# Create a dictionary
my_dict = {'a': 1, 'b': 2, 'c': 3}

# Remove the key 'b' and its associated value from the dictionary
del my_dict['b']
print(my_dict)

使用 remove() 方法

remove() 方法仅适用于列表,当您希望按元素的确切值而非索引来移除元素时使用。若该元素在列表中出现多次,此方法会移除首次出现的那个。下面的代码将打印 [1, 3, 4, 5]。

# Initialize a list with integers from 1 to 5
my_list = [1, 2, 3, 4, 5]

# Remove the element with the value 2 from the list
my_list.remove(2)
print(my_list)

总结

pop() 方法是 Python 中一种格外简洁且多功能的特性,用于从列表和字典中移除元素,并在编程中有各种实用场景。处理列表和字典时,pop() 方法尤其重要,因为它会返回被移除的元素,而这往往正是您所需要的行为。

作为数据分析师,我建议您查看 DataCamp 的 Python Fundamentals 和 Python Programming 技能路径,以提升用于数据分析的 Python 技能。我也鼓励您了解我们的 Data Analyst with Python 职业路径,持续构建实用且与岗位相关的技能。

Allan Ouko

作者

Allan Ouko

数据科学技术写作者,具备数据分析、商业智能和数据科学的一线实践经验。我撰写以行业为导向的实用内容,涵盖 SQL、Python、Power BI、Databricks 和数据工程,并以真实的分析工作为基础。我的写作兼顾技术深度与业务影响,帮助专业人士将数据转化为自信的决策。

常见问题解答

pop() 方法的作用是什么?

pop() 方法会从列表或字典中移除并返回一个元素。

pop() 方法中的 IndexError 是什么?

当您尝试用超出范围的索引移除元素时,会发生 IndexError。

有哪些可以替代 pop() 方法的做法?

remove() 方法和 del 关键字是从列表或字典中移除元素的替代方法。

pop() 与 remove() 方法有什么区别?

pop() 方法按索引从列表或字典中移除并返回指定元素;而 remove() 方法按值从列表或字典中移除元素,且不返回该值。

pop() 方法的时间复杂度是多少?

pop() 方法的默认时间复杂度为 O(1),即常数时间,效率较高。

pop() 方法能用于列表和字典之外的数据结构吗?

是的,pop() 方法也可用于 Python 中的集合(set)和字节数组(bytearray)。对于集合,set.pop() 会移除并返回一个任意元素,因为集合是无序的。对于字节数组,bytearray.pop(index) 会移除并返回指定索引处的元素,与在列表中的用法类似。

主题