list--pop()

发现一个神奇的问题:

>>> list = range(101)

 >>> type(list)
 <class 'range'>

>>> list = [1,2,3]
>>> type(list)
<class 'list'>
>>> list
[1, 2, 3]
>>> list.pop(a)
2
>>> list.pop(a)
3
>>> list.pop(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop index out of range
>>> list.pop(0)
1
>>> list
[]
>>> list.pop(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: pop from empty list
>>>

1.range()生成的不是list类型,而是range类型

2.pop()应该是弹出对应下标的元素啊?怎么pop(a)像是等价于pop(1)呢?

转载于:https://www.cnblogs.com/cucumbermongo/p/10330662.html

### 关于 `list.pop()` 方法的使用 `list.pop()` 是 Python 中用于移除列表中的元素并返回该元素的方法。默认情况下,它会移除并返回列表中的最后一个元素,但如果提供索引参数,则可以指定要移除的具体位置。 以下是有关 `list.pop()` 的详细说明: #### 默认行为 当调用 `pop()` 而不传递任何参数时,方法会删除并返回列表中的最后一个元素[^1]。 ```python my_list = [1, 2, 3, 4] last_element = my_list.pop() print(last_element) # 输出: 4 print(my_list) # 输出: [1, 2, 3] ``` #### 使用索引参数 可以通过向 `pop(index)` 提供一个整数作为索引来指定要移除的元素的位置。如果索引超出范围,则会抛出 `IndexError` 异常。 ```python my_list = ['a', 'b', 'c'] second_element = my_list.pop(1) print(second_element) # 输出: b print(my_list) # 输出: ['a', 'c'] ``` #### 常见错误及其解决方案 1. ** IndexError**: 如果尝试从空列表中弹出元素或者提供了越界的索引值,程序将引发 `IndexError`。因此,在执行操作前应验证列表长度是否满足需求。 ```python my_empty_list = [] try: element = my_empty_list.pop() # 将触发异常 except IndexError as e: print(f"Caught an exception: {e}") ``` 2. **负数索引支持**: 可以通过负数来访问倒序排列的项目;例如 `-1` 表示最后一位,而 `-2` 则代表倒数第二位等。 ```python another_list = ["apple", "banana", "cherry"] last_item = another_list.pop(-1) second_last = another_list.pop(-1) print(last_item) # cherry print(second_last) # banana ``` #### 性能考虑 对于非常大的数据集来说,频繁地从前端或中间部分调用 `pop(i)` (其中 i 不接近末端),可能会降低性能因为这涉及到重新安排剩余项的位置。 ```python large_list = list(range(10000)) for _ in range(9999): large_list.pop(0) # 这种方式效率较低 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值