Repository navigation
tricky question_3 #9
|
You have a list of even numbers, and you want to delete every even number from it. You write a loop that removes each one it finds. The list should end up empty. python a) Predict: Is the final list empty? Write down what you think it contains. |
Replies: 1 comment
a) Predicted outputNo, the list is not empty. Half the values survive. b) Trace by handA
The loop never looks at 4 or 8.
The core problem is mutating a list while iterating over it. c) Two fixes1) Loop over a copy The loop walks the copy, which never changes, while 2) Build a new list with a comprehension This keeps only the odd numbers, so every even number is dropped. Which I'd pick for real code: the comprehension.
|
a) Predicted output
No, the list is not empty. Half the values survive.
b) Trace by hand
A
forloop over a list uses a hidden index that goes up by 1 each pass. When you remove an item, the remaining items shift left, but the index still moves forward.The loop never looks at 4 or 8.