I’m trying to understand what is the difference here? Is function range() better to be used here? Or why will we use range() if we cand do simply like (code #2)
Code 1:
a = [1, 2, 3, 4, 5]
for elem in range(len(a)):
print(elem)
Code 2:
a = [1, 2, 3, 4, 5]
for elem in a:
print(elem, end=' ')
>Solution :
Short Answer
Both methods are valid ways to iterate over a list in Python, but they are used in different scenarios.
So the choice between the two methods depends on what you need to do with the list. If you only need the values and not the indices, the second method (for elem in a) is simpler and more idiomatic in Python. If you need the indices, the first method (range(len(a))) is appropriate.
Also as @samwise mentioned in the comments the enumerate function lets you work with both the indices and the values if you wanted.
Additional Details
-
Using
range(len(a))will give you the index of each element in the list. This is useful when you not only need the value of each element, but also its position in the list. In your example,elemwill be the index of each element, not the element itself. You would use this method if you want to manipulate the list in place or if you need to know the index of each element for some reason.Code 1:
a = [1, 2, 3, 4, 5] for i in range(len(a)): print(i)This will print the indices (0, 1, 2, 3, 4) not the values of the list.
-
Using
for elem in awill give you each element in the list directly. This is a more Pythonic way to iterate over a list when you don’t need to know the index of each element. In your example,elemwill be each element in the list.Code 2:
a = [1, 2, 3, 4, 5] for elem in a: print(elem, end=' ')This will print the values (1, 2, 3, 4, 5) of the list.