wemake-python-styleguide
wemake-python-styleguide copied to clipboard
Forbid implicit slice
Rule request
Forbid looping constructs over indexes that are equivalent to slice operations.
Thesis
I recently encountered a point in my code where I was using a comprehension to iterate over a range
to index into a list. Here is a basic example that currently passes all checks:
my_list = [1, 2, 3, 4, 5]
# Wrong:
my_sublist = [my_list[index] for index in range(1, 4)]
# Right:
my_sublist = my_list[1:4]
A trickier example closer to what I found:
some_text = 'Python!'
an_index = 4
# Wrong (but fails on Jones complexity):
subset = {some_text[index] for index in range(an_index - 1, an_index - 4, -1)}
# Right:
subset = set(some_text[an_index - 3:an_index])
Reasoning
These are redundant, probably slower, and harder to read.