Yes you are correct that former one iterates through all items in list “lst”. But wrong about the other one.
len(lst) returns the length of the argument passed in (in this case length of list).
For ex,
lst = ["hi", "hello", "new", "fourth"]
print(len(lst))
# prints out 4 as it is clear that length (or number of elements) in list "lst" is 4
Now, range() function generates an iterable object. Confused? Let’s make this more simpler
We know everything is object in python. So any list is also a object. Range() generates a list object.
It takes 1 necessary and 2 optional arguments. All three needs to be integers.
So If we do like this
lst = range(5)
print(lst)
# Will print range(0, 5). This is surely not a list. But let's understand this first
range(0, 5) means every number between 0 (including) and 5 (excluding). A by default step size (difference between each number) of 1. So it would be like 0, 1, 2, 3, 4
. How to get a list from this? Simple,
lst = list(range(5))
print(lst)
# gives [0, 1, 2, 3, 4]
I hope by now range() would be clear. (Why did I explain range()? because it’s important in your problem)
Using range() with list() around it generates a object which can be iterated upon, meaning we can loop on it.
In your case, len(lst) will give a integer (length or num of elements in lst) and using range() on len(lst) will give a iterable object which is a list of numbers from 0 to len(lst) , not including len(lst), with step size 1.
Some example code:
lst = [67, 84, 36, 37, 76, 37]
for x in lst:
print(x)
""" prints:
67
84
36
37
76
37
"""
for x in range(len(lst)):
print(x)
""" prints:
0
1
2
3
4
5
"""
I hope you understood.
Happy Coding
.