flake8-simplify icon indicating copy to clipboard operation
flake8-simplify copied to clipboard

SIM113: Use enumerate

Open MartinThoma opened this issue 4 years ago • 6 comments

Explanation

Use 'enumerate' to get a running number over an iterable.

Example

# Bad
idx = 0
for el in iterable:
    ...
    idx += 1

# Good
for idx, el in enumerate(iterable):
    ...

MartinThoma avatar Oct 21 '20 08:10 MartinThoma

This is a false-positive:

for x in xs:
    cm[x] += 1

MartinThoma avatar Nov 17 '20 22:11 MartinThoma

This is another false possitive

results = []
next_ = 0
for i in range(10):
        if i % 2 == 0:
            continue

        results[next_] = i
        next_ += 1

pablojadz avatar May 13 '21 16:05 pablojadz

@pablojadz Could you please run pip install flake8-simplify --upgrade and test again? You should have flake8-simplify==0.14.1 and this issue should not exist anymore.

MartinThoma avatar May 13 '21 20:05 MartinThoma

I believe I have another false-positive:

pos = len(output) - token[1]
for __ in range(token[0]):      
    output += output[pos]   
    pos += 1                

This code appends token[0] characters from position pos to the end of the string output. (This is a common pattern in LZ-style decompressors.)

specke avatar Sep 18 '22 20:09 specke

Another possible issues

for idx, el in enumerate([]): pass
print(idx) --> NameError

I would propose to silence the error, when the loop variable is used after the loop

kasium avatar Jul 19 '23 07:07 kasium