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

This page is not yet available in Spanish. We are working on its translation.
If you have any questions or feedback about our current translation project, feel free to reach out to us!

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

PREVIEWING: rtrieu/product-analytics-ui-changes