range with for loop
1 min read ·
The
range() function is most commonly used with the for loop to repeat a block of code a fixed number of times.It provides a clean and controlled way to handle iteration.
Iterating Using range()
When used with a
for loop, range() generates numbers sequentially and assigns each value to the loop variable.The loop runs five times using values generated by
range().This approach is preferred when the number of iterations is known in advance.
Index Based Looping
range() is often used to access elements of a list using indexes.Here
range(len(languages)) generates valid index values for the list.This technique allows controlled access to elements using their positions.
Best Practices
Use
range() when iteration count is fixed.
Avoid using range() for direct iteration over elements when element values are sufficient.
Prefer direct iteration when indexes are not required.Pro Tip
Use index based looping only when index values are actually needed.
Using
range() with for loops ensures predictable and readable iteration behavior.