Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 873
Alex44 Avatar asked Nov 18 '18 07:11

Alex44


3 Answers

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.

like image 130
user4815162342 Avatar answered Oct 21 '22 22:10

user4815162342


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}')
like image 2
buran Avatar answered Oct 21 '22 20:10

buran


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.

like image 2
Jeronimo Avatar answered Oct 21 '22 22:10

Jeronimo