Python: iterate through list using range method vs using a for Loop

1. Iterate through the list using range()

The range() method returns a sequence of integers from the upper limit (start) to the lower limit (stop, but exclude). It can be used in combination with a for loop to traverse and iterate over a list in Python

ls = [1,2,3,4,5]
for idx in range(len(ls)):
    print(ls[idx])

2. Iterate through the list using a For Loop:

Image 1: Python loops (credit: debug.to)

The For loop can be used to iterate through a list directly and straightforward

ls = [1,2,3,4,5]
for val in ls:
    print(val)

3. The difference between the two methods

The example I used above procedure the same result: print all elements from the list. However, they will differ if we want to modify the value of items in the list.

For example with range() method:

ls = [1,2,3,4,5]
for idx in range(len(ls)):
    ls[idx] += 1

Then the ls will be changed to ls = [2,3,4,5,6]

But with the for loop:

ls = [1,2,3,4,5]
for val in ls:
    val += 1

The original list is unchanged

Explain: numeric types are immutable. The += operator in the second example creates a new instance of val, but doesn't change the reference to the original object in ls. Meanwhile, in the first example, ls[idx] changes the reference to element idx, which changes the original list. Therefore, be careful when using the methods even in some cases they give the same result, but in other cases, they don't. Happy coding :)