Python list comprehension - access last created element?

You could have done this using reduce(). It's not list comprehension, but it's the functional style approach:

cipher = []
def f(previous, element):
    previous = element ^ previous ^ key
    cipher.append(previous)
    return previous
reduce(f, message, initialization_value)

It isn't any prettier than the plain loop in this case though.


As a generator:

def cypher(message, key, seed):
    for element in message:
        seed = element ^ seed ^ key
        yield seed

list(cypher(message, key, initial_seed))

It probably can be done; see The Secret Name of List Comprehensions. It's very much not pythonic, though.


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.

Tags:

Python