Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list comprehension - access last created element?

Tags:

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?

like image 534
Matt Avatar asked Apr 27 '09 18:04

Matt


1 Answers

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.

like image 124
Eli Courtwright Avatar answered Dec 06 '22 12:12

Eli Courtwright