Simplify Negative Index¶
Sourcery refactoring id: simplify-negative-index
¶
Description:¶
Replaces a[len(a)-1]
with negative index lookup a[-1]
Before:¶
a = [1, 2, 3]
last_element = a[len(a) - 1]
After:¶
a = [1, 2, 3]
last_element = a[-1]
Explanation:¶
In Python you can access the end of a list by using negative indices. So
my_list[-1]
gets the final element, my_list[-2]
gets the penultimate one and
so on. Once you know the trick, reading code that uses it is much easier than
the alternative.