Simplify Negative Index
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: simplify-negative-index
Section titled “Sourcery refactoring id: simplify-negative-index”Description:
Section titled “Description:”Replaces a[len(a)-1] with negative index lookup a[-1]
Before:
Section titled “Before:”a = [1, 2, 3]last_element = a[len(a) - 1]After:
Section titled “After:”a = [1, 2, 3]last_element = a[-1]Explanation:
Section titled “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.