Python / Core Python Fundamentals Interview Questions
How does the for loop work in Python, and what is the role of range()?
Python's for loop iterates over any iterable — lists, strings, tuples, dictionaries, files, generators, and more. Unlike C-style for loops with an index counter, Python's loop just hands you each item in turn.
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Iterating a string character by character
for ch in 'hello':
print(ch)range() generates a lazy sequence of integers and is the standard way to loop a fixed number of times. It takes up to three arguments: range(stop), range(start, stop), or range(start, stop, step). It never stores the full list in memory — it yields one integer at a time, making it memory-efficient even for range(10_000_000).
for i in range(5): # 0 1 2 3 4
print(i)
for i in range(2, 10, 2): # 2 4 6 8
print(i)When you need both the index and the value, use enumerate() instead of manually tracking a counter:
for idx, fruit in enumerate(fruits, start=1):
print(idx, fruit) # 1 apple 2 banana 3 cherrybreak exits the loop early; continue skips to the next iteration. A for loop can also have an else clause that runs only if the loop completed without hitting break — useful for search patterns.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
