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 in
Here is an example how to access the last and next created elements in a list comprehension using enumerate.
The previous value...
Here -1 is the offset and None is the default value.
A = ['A','B','C','D','E','F','G','H','I','J']
[(A[i-1] if (i-1) >= 0 else None,x) for i,x in enumerate(A)
Output as tuple (Previous, Current)
[(None, 'A'), ('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I'), ('I', 'J')]
The next value...
A = ['A','B','C','D','E','F','G','H','I','J']
[(x, A[i+1] if (i+1) < len(A) else None) for i,x in enumerate(A)]
Output as tuple (Current, Next)
[('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'E'), ('E', 'F'), ('F', 'G'), ('G', 'H'), ('H', 'I'), ('I', 'J'), ('J', None)]
This is very similar to the lag() and lead() analytical functions in sql.