Python list comprehension – access last created element?

There isn’t a good, Pythonic way to do this with a list comprehension. The best way to think about list comprehensions is as a replacement for map and filter. In other words, you’d use a list comprehension whenever you need to take a list and

  • Use its elements as input for some expression (e.g. squaring the elements)

  • Remove some of its elements based on some condition

What these things have in common is that they each only look at a single list element at a time. This is a good rule of thumb; even if you could theoretically write the code you showed as a list comprehension, it would be awkward and unpythonic.

Leave a Comment