You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
-[> Beware of default mutable arguments!](#-beware-of-default-mutable-arguments)
63
63
-[> Catching the Exceptions](#-catching-the-exceptions)
@@ -1420,7 +1420,7 @@ Deleted!
1420
1420
1421
1421
---
1422
1422
1423
-
### > Deleting a list item while iterating
1423
+
### > Deleting a list item while iterating/迭代列表时删除元素
1424
1424
1425
1425
```py
1426
1426
list_1 = [1, 2, 3, 4]
@@ -1453,30 +1453,30 @@ for idx, item in enumerate(list_4):
1453
1453
[2, 4]
1454
1454
```
1455
1455
1456
-
Can you guess why the output is `[2, 4]`?
1456
+
你能猜到为什么输出是 `[2, 4]` 吗?
1457
1457
1458
-
#### 💡 Explanation:
1458
+
#### 💡 说明:
1459
1459
1460
-
* It's never a good idea to change the object you're iterating over. The correct way to do so is to iterate over a copy of the object instead, and `list_3[:]` does just that.
- The list iteration is done index by index, and when we remove `1` from `list_2` or `list_4`, the contents of the lists are now `[2, 3, 4]`. The remaining elements are shifted down, i.e., `2` is at index 0, and `3` is at index 1. Since the next iteration is going to look at index 1 (which is the `3`), the `2` gets skipped entirely. A similar thing will happen with every alternate element in the list sequence.
* Refer to this StackOverflow [thread](https://stackoverflow.com/questions/45946228/what-happens-when-you-try-to-delete-a-list-element-while-iterating-over-it) explaining the example
1479
-
* See also this nice StackOverflow [thread](https://stackoverflow.com/questions/45877614/how-to-change-all-the-dictionary-keys-in-a-for-loop-with-d-items) for a similar example related to dictionaries in Python.
0 commit comments