Is it possible to access the previous element generated in a list comprehension?
I am working on some toy encryption stuff. Given the key as an arbitrarily large integer, an initialization value, and a list of elements as the message to encrypt. I need to xor each element with the previous ciphered element and the key. The following loop would do.
previous = initialization_value
cipher = []
for element in message:
previous = element ^ previous ^ key
cipher.append(previous)
I feel like it should be possible to turn this into a list comprehension, but I am not exactly sure how to handle both the initial value or accessing the previous value generated.
Is it possible and if so what would the comprehension be?
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
mapandfilter. In other words, you’d use a list comprehension whenever you need to take a list andUse 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.