For Loop in Python: Syntax, range(), and Worked Examples
Learn how Python's for loop iterates over lists, strings, and ranges. Covers range(), break, continue, nested loops, and placement coding patterns.
Python’s for loop iterates directly over a sequence, no index counter required, making it the standard tool for placement coding questions involving lists, strings, and ranges.
The loop visits each element in turn, assigns it to the loop variable, runs the indented block, then moves to the next element. When the sequence runs out, the loop ends. This design handles the bookkeeping automatically.
What a for loop does
In C, Java, and C++, a for loop typically manages an index explicitly. You write something like int i = 0; i < n; i++ and track the position yourself. Python takes a different approach: you name the sequence, and the interpreter handles the position.
This makes Python for loops shorter to write and removes an entire class of off-by-one errors. The tradeoff is that when you genuinely need the index, you ask for it explicitly using enumerate(). Most placement problems don’t need the index at all.
Three situations where a for loop is the right tool:
- You need to process each element of a list or tuple.
- You need to examine each character in a string.
- You need to repeat an operation a fixed number of times using
range().
The loop body can contain any code: a print statement, a calculation, a conditional, another loop. Python does not restrict what goes inside.
The for loop syntax
The Python 3 documentation defines the for loop as iterating over the items of any sequence in the order they appear.
The syntax:
for variable in sequence:
# code block runs once per element
Three parts:
variable— the name that holds the current element on each iteration. Any valid Python identifier works. Common choices:item,i,num,char,element.sequence— any Python iterable: list, tuple, string, dictionary, the output ofrange(), or a file object.- Indentation — the body must be indented consistently. Four spaces is the Python standard. Python uses indentation instead of braces to mark code blocks.
One important note: the Python documentation advises against modifying the sequence while iterating over it. Doing so produces unpredictable results. If you need to modify a list while looping, iterate over a copy and build a new list instead.
Iterating over lists, strings, dictionaries, and range()
Lists
A list is the most common sequence to iterate over in placement coding rounds.
scores = [85, 92, 78, 95]
for score in scores:
print(score)
Output:
85
92
78
95
Each value is visited in order. The loop variable score takes the value 85 on the first iteration, 92 on the second, and so on.
Strings
Strings are sequences of characters. A for loop visits each character in turn.
for char in "FACE":
print(char)
Output:
F
A
C
E
This character-by-character pattern is the foundation of palindrome checks, vowel counts, and character-classification problems. The basic Python programs collection includes ready-to-run examples that use this pattern to check for vowels and classify character types.
Dictionaries
Iterating over a dictionary gives you access to keys, values, or both, depending on which method you call.
result = {"name": "Priya", "branch": "CSE", "score": 92}
for key, value in result.items():
print(key, ":", value)
Output:
name : Priya
branch : CSE
score : 92
Three iteration methods:
.items()— yields (key, value) tuples on each iteration..keys()— yields only the keys..values()— yields only the values.
Python 3.7 and later guarantees that dictionary iteration follows insertion order.
Using range()
The range() built-in generates an immutable sequence of integers without allocating a full list in memory. This makes it efficient for large counts.
Three forms:
range(stop)— integers from 0 up to, but not including, stop.range(start, stop)— integers from start up to, but not including, stop.range(start, stop, step)— every step-th integer from start to stop.
# Integers 0 to 4
for i in range(5):
print(i)
Output: 0, 1, 2, 3, 4 (one per line).
# Odd integers from 1 to 9
for i in range(1, 10, 2):
print(i)
Output: 1, 3, 5, 7, 9.
# Countdown from 5 to 1
for i in range(5, 0, -1):
print(i)
Output: 5, 4, 3, 2, 1.
A negative step reverses direction. Countdown loops using range(n, 0, -1) appear in pattern-printing questions in TCS and Infosys placement rounds.
Control flow inside a for loop: break, continue, and pass
Three statements change how the loop progresses. Each behaves differently when the condition fires.
break
break exits the loop immediately, before processing any remaining elements.
scores = [85, 92, 55, 78]
for score in scores:
if score < 60:
break
print(score)
Output:
85
92
The loop stops the moment it encounters 55. The value 78 is never reached.
continue
continue skips the rest of the current iteration and moves to the next element.
scores = [85, 92, 55, 78]
for score in scores:
if score < 60:
continue
print(score)
Output:
85
92
78
55 is skipped. The loop moves on to 78 and processes it normally.
pass
pass is a syntactic placeholder that does nothing. Python requires an indented block wherever control flow branches; pass satisfies that requirement without any action.
scores = [85, 92, 55, 78]
for score in scores:
if score < 60:
pass # placeholder — handle failing scores later
print(score)
Output:
85
92
55
78
Unlike continue, pass does not skip anything. The print(score) line executes for every element, including 55.
The three statements compared:
| Statement | Immediate effect | Remaining iterations |
|---|---|---|
break | Exit the loop entirely | Not executed |
continue | Skip current iteration body | Continue with next element |
pass | Do nothing | Current iteration continues |
Nested for loops
A for loop placed inside another for loop. The inner loop runs completely before the outer loop advances.
rows = ["A", "B", "C"]
cols = [1, 2]
for row in rows:
for col in cols:
print(row, col)
Output:
A 1
A 2
B 1
B 2
C 1
C 2
The outer loop has 3 iterations. The inner loop has 2 iterations per outer step. Total executions of the inner body: 3 times 2 equals 6.
This multiplication property matters in placement tests. A nested loop over an n-element list inside an m-element list runs in O(m times n) time. Recognising this helps with complexity estimation questions that appear in Wipro and Cognizant aptitude rounds.
Pattern-printing questions almost always use nested loops. The outer loop controls how many rows to print; the inner loop prints the characters in each row.
Placement coding patterns with for loops
The for loop is the building block for standard problems across TCS, Infosys, Wipro, and Cognizant coding rounds.
- Sum of array elements — initialise a total to 0, then add each element inside the loop body. The sum of array in Python article walks through this pattern with a step-by-step implementation.
- Armstrong number check — loop over the digit string of a number, raise each digit to the power of the digit count, and accumulate. The Armstrong number check article covers the full algorithm with verified digit-power examples for 153, 370, 371, and 407.
- Alphabetical sort — a for loop that compares and swaps adjacent characters drives the bubble sort approach for strings. The alphabetical sort program shows this in full.
- Pattern printing — nested loops generate triangles, pyramids, and diamonds. Each row is one outer-loop iteration; each character in a row is one inner-loop iteration.
- Factorial and power — replace
total += itemwithtotal *= iteminside the loop body. Same structure, different accumulator operation.
The for item in sequence pattern this article covers is also the shape of batch LLM API calls: iterate over a list of inputs, call the model for each, collect the responses. TinkerLLM is a hands-on Python LLM playground at ₹299 where that same iteration loop runs against real language models, so you see the loop-and-collect structure applied to a context beyond placement prep.
Primary sources
Frequently asked questions
What is the syntax of a for loop in Python?
The syntax is: for variable in sequence: followed by the indented code block. The variable takes the value of each element in the sequence on each iteration. Indentation (4 spaces) marks the loop body.
What does range() return and how is it used in a for loop?
range(stop) generates integers from 0 up to but not including stop. range(start, stop) starts from start. range(start, stop, step) adds a step size. range(5) gives 0, 1, 2, 3, 4. The sequence is generated lazily, without allocating a list in memory.
What is the difference between break and continue in a Python for loop?
break exits the entire loop immediately, even if elements remain in the sequence. continue skips only the rest of the current iteration and moves to the next element. After break, no further iterations run. After continue, the loop proceeds normally.
How do you iterate over a dictionary with a for loop in Python?
Use dict.items() to get (key, value) pairs: for key, value in my_dict.items(). Use dict.keys() for keys alone, or dict.values() for values alone. Python 3.7 and later guarantees insertion-order for dictionary iteration.
What is a nested for loop in Python?
A nested for loop is a for loop inside another for loop. The inner loop runs completely for each single iteration of the outer loop. An outer loop of m iterations and an inner of n iterations gives m times n total executions of the inner body.
How does pass differ from continue in a Python for loop?
continue skips the remaining lines of the current iteration and moves directly to the next element. pass does nothing at all — it is a syntactic placeholder when Python requires a code block but no logic is needed yet. After pass, all remaining lines in the loop body still execute for that iteration.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)