Do not use for i in range(len(<array>))

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。
翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください

Metadata

ID: python-best-practices/no-range-loop-with-len

Language: Python

Severity: Error

Category: Best Practices

Description

Do not iterate over an array using for in range(len(array)). Use instead for i in array.

Learn More

Non-Compliant Code Examples

import random
import string

DEFAULT_CHAR_STRING = string.ascii_lowercase + string.digits


def generate_random_string(chars=DEFAULT_CHAR_STRING, size=20):
    return "".join(random.choice(chars) for _ in range(size))


NORMALIZED_SIZE = 8


def normalize(s):
    builder = []
    for i in range(NORMALIZED_SIZE):
        builder.append(s[i].capitalize())
    return "".join(builder)


FORBIDDEN_WORDS = set(["bad1", "bad2"])


def filter_forbidden_tags(tags):
    for i in range(len(tags)):
        if tags[i].tag in FORBIDDEN_WORDS:
            del tags[i]
    return tags
for i in range(len(tab)):  # iterate directly over the array
  bla(tab[i])
for i in range(len(tab)):  # iterate directly over the array
  bla(tab[i])
for i in range(len(tab)):  # iterate directly over the array
  tab[i] = bla

Compliant Code Examples

for i, _ in enumerate(lst):
   print(i)

for i in range(len(lst)):
   print(i)
   plop = tab[i]
for i in tab:
  bla(i)
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis