Avatar ·

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

Avatar ·

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:

  1. The return value is saved (but not returned), then the execution flow moves to the finally block.
  2. All actions inside the finally block are executed, after which the previously saved value is returned.
  3. If the finally block contains

Log in to leave an answer

Blogs