Question

[Solved] Why we use range(len) in for loop in python?

I have started learning python and now learning python for loop. I am using online source to learn python. But i am little but confused about for loop.

The output of

list = ["geeks", "for", "geeks"]
for index in range(len(list)):
    print (list[index])

and

list = ["geeks", "for", "geeks"]
for i in list:
    print(i)

are same then why to use range(len) method?

Thanks in advance.

Enquirer: Alex44

||

Solution #1:

For such simple case, for ind in range(len(sequence)) is generally considered an anti-pattern. The are cases when it’s useful to have the index around, though, such as when you need to assign back to the list:

for ind in range(len(lst)):
    elem = lst[ind]
    # ... Do some processing
    lst[ind] = processed_elem

Even in that case, range(len(...)) is better expressed with enumerate:

for ind, elem in enumerate(lst):
    # ... Do some processing
    lst[ind] = processed_elem

Also, as already pointed out in a comment, it’s recommended to avoid variable names that clash with built-ins, such as list.

Respondent: user4815162342

Solution #2:

you should never use the first one, it’s non-pythonic. Use the second one. If for whatever reason you need the index, use enumerate, e.g.

for index, item in enumerate(some_list):
    print(f'Item with index {index} is {item}')
Respondent: buran

Solution #3:

While the latter is definitiely the way to go as long as it fits your needs since its clear and pythonic, there are cases where you really need the index of the element.

One example are sorting algorithms, like this BubbleSort here (src):

def bubbleSort(arr):
    n = len(arr)

    # Traverse through all array elements
    for i in range(n):

        # Last i elements are already in place
        for j in range(0, n-i-1):

            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j+1] :
                arr[j], arr[j+1] = arr[j+1], arr[j]

Here the list indices of sequential elements are used to swap their positions in the list if their sort order is incorrect, while the position in the list is something the pure values of the elements in a for elem in arr loop don’t have any connection to anymore. Therefore in such cases you won’t get around using the range over the list’s len or similar, so that’s not un-pythonic by defintion.

Last but not least, a good combination if you need both the index and the value is Python’s enumerate.

for index, value in enumerate(arr):
     print(index, value)

Although one could use it in the above BubbleSort example, you’d start mixing value variables with arr[index] expressions, which is not a good idea for the readability of the code. So here, too, it depends very much on the situation if it makes sense to use the one construct or the other, there’s no definite choice.

Respondent: Jeronimo

Solution #4:

Like others, I can’t think of many use cases for for idx in range(len(x)):. The only one that really pops to mind is if you need to remove elements from x over the course of the for loop (in which case, as pointed out in the comments, you should go backwards), or you want to do a number of loops equal to len(x) for some reason unconnected to operations on x.

But yes, generally don’t use for _ in range(len(x)): if you are iterating over x.

Respondent: NotAnAmbiTurner

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy