list index complement

Go Back home

Many algorithms require you to contemplate list elements symmetrically both front from to back, and back to front. This can be done using "list index complement".

Say you have an input list:

1 A = [1,2,3,4]

And would you like to generate this output:

1 [(1,4), (2,3), (3,2), (4,1)]

One approach may be to use back to front indexing:

1 A = [1,2,3,4]
2 for i in range(len(A)):
3     print((A[i], A[len(A)-i-1]))

The len(A)-i-1 looks cumbersome to say the least. Remember that list indexing in Python works fine with negative numbers; so this would look cleaner:

1 A = [1,2,3,4]
2 for i in range(len(A)):
3     print((A[i], A[-i-1]))

However that -i-1 still doesn't sit right. This is when the complement comes into play:

1 A = [1,2,3,4]
2 for i in range(len(A)):
3     print((A[i], A[~i]))

Output:

1 (1, 4)
2 (2, 3)
3 (3, 2)
4 (4, 1)

Using list comprehensions:

1 result = [(A[i], A[~i]) for i in range(len([1,2,3,4]))]
2 print(result)

Output:

1 [(1, 4), (2, 3), (3, 2), (4, 1)]