This product is not supported for your selected Datadog site. ().
Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

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 Security

PREVIEWING: ida.adjivon/rtrieu/DOCS-10715-ET-standalone