Remove list elements by condition
📁 method, List, Advanced Python Topics
There is a list
lst = [0, 95, 0, 76, 0, 23, 68, 0, 23, 156, 95]It is required to remove each element that follows 0
to get the output:
new_lst = [0,0,0,68,0,156,95]The str.index() method does not help me, because it returns only the first occurrence
Short answer: the block inside finally will execute in any case, regardless of what happens inside the try, except, else blocks, so the value 2 will be returned.
If we go deeper:
According to the specification, when a return statement is encountered inside the try/except/else blocks and there is a finally statement after it, the function execution is not interrupted, but the following happens approximately:
- The return value is saved (but not returned), then the execution flow moves to the
finallyblock. - All actions inside the
finallyblock are executed, after which the previously saved value is returned. - If the
finallyblock contains
Log in to leave an answer