Junior — Middle
What type of loop is preferable for iterating over collection elements?
sobes.tech AI
Answer from AI
In Python, it is preferable to iterate over the elements of a collection directly using a for loop, rather than over indices. This is more readable, safer, and efficient.
Example:
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Using indices (for i in range(len(collection))) is justified only if the index itself is needed or if elements need to be modified by index.