[Python] Is there a need for range(len(a))?

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    One frequently finds expressions of this type in python questions on SO. Either for just accessing all items of the iterable

    for i in range(len(a)):
    print(a)


    Which is just a clumbersome way of writing:

    for e in a:
    print(e)


    Or for assigning to elements of the iterable:

    for i in range(len(a)):
    a = a * 2


    Which should be the same as:

    for i, e in enumerate(a):
    a = e * 2
    # Or if it isn't too expensive to create a new iterable
    a = [e * 2 for e in a]


    Or for filtering over the indices:

    for i in range(len(a)):
    if i % 2 == 1: continue
    print(a)


    Which could be expressed like this:

    for e in a [::2]:
    print(e)


    Or when you just need the length of the list, and not its content:

    for _ in range(len(a)):
    doSomethingUnrelatedToA()


    Which could be:

    for _ in a:
    doSomethingUnrelatedToA()


    In python we have enumerate, slicing, filter, sorted, etc... As python for constructs are intended to iterate over iterables and not only ranges of integers, are there real-world use-cases where you need in range(len(a))?

    Continue reading...

Compartilhe esta Página