This tutorial will teach you all about using for loops in Python with code examples.
In programming, loops help you repeat a specific set of statements. You’ll use for loops for definite iterations when:
- you know you’ll be working with a sequence with a finite number of elements
- you see the number of repetitions beforehand
This tutorial will teach you all about working with for loops in Python. You’ll start by learning the syntax and simple iterations using a for loop. Then, you’ll learn about processing command line arguments, using loop control statements, and more.
Let’s get started…
Syntax of Python for Loop

The generic syntax for using the for loop in Python is as follows:
for item in iterable:
# do something on item
statement_1
statement_2
.
.
.
statement_n
In the above syntax:
- item is the looping variable.
- iterable denotes any Python iterable such as lists, tuples, and strings.
- statement_1 through statement_n denote the statements in the loop body.
Note: Be sure to add a colon (:
) after the name of the iterable and indent all statements in the loop body by four spaces.
Common for Loop Constructs in Python

When using a for loop:
- You can access the items directly using the syntax discussed in the previous section.
- You can use for loop in conjunction with Python built-in functions such as
range()
andenumerate()
.
We’ll cover them in this section.
Using for Loop to Access Elements
To improve readability, you should pick a looping variable indicative of what the list contains. For example, in the example below, nums
is a list of numbers that we use num
as the looping variable. Notice how for num in nums:
is intuitive and easy to read.
nums = [4,5,9,1,3]
for num in nums:
print(num)
# Output
4
5
9
1
3
Adding a few more examples, you can use for fruit in fruits:
and for student in students:
when looping through fruits
and students
list, respectively.
Using for Loop with the range() Function
When you want to access a list item through its index, you can use the range()
function.
In Python,
range(start, stop, step)
returns a range object, which you can loop through to get the indices:start
,start + step
, and so on, up to but not includingstop
.
for i in range(len(nums)):
print(nums[i])
# Output
4
5
9
1
3
You can also use the range()
function to generate a sequence of numbers to loop through. In the example below, we set the optional step
parameter to 2. So we get numbers from 10 up to but not including 20, in steps of 2.
for i in range(10,20,2):
print(i)
# Output
10
12
14
16
18
Using for Loop with the enumerate() Function
When you want to loop through an iterable and access the items and their indices simultaneously, you can use the enumerate() function.
Here’s an example.
for idx, num in enumerate(nums):
print(f"{idx}:{num}")
# Output
0:4
1:5
2:9
3:1
4:3

How to Read Items from Lists Using for Loop in Python
To loop through Python lists using for loop, you can use the generic syntax from the previous section.
In the example below, nums
is iterable, and num is the looping variable.
nums = [4,5,9,1,3]
for num in nums:
print(f"{num} times 3 is {num*3}") # action on each num
# Output
4 times 3 is 12
5 times 3 is 15
9 times 3 is 27
1 times 3 is 3
3 times 3 is 9
How to Loop Through Strings Using for Loop in Python
Python strings are iterables and you can perform looping, indexing, slicing, and more.
Note: Python does not have a built-in character data type. So you can treat a character as a string of length one.
my_string = "Code"
for char in my_string:
print(char)
# Output
C
o
d
e
How to Loop Through Arrays Using for Loop in Python

You can loop through arrays using loops and nest for loops.
In the code snippet below, array1 is a nested list containing smaller lists as its elements. So looping through array1 gives each row, as shown below.
array1 = [[2,3],[7,8]]
for row in array1:
print(row)
# Output
[2, 3]
[7, 8]
To access individual elements in each row, you can use another for
loop.
array1 = [[2,3],[7,8]]
for row in array1:
for elt in row:
print(elt)
In the above code cell:
- The outer for loop helps you index into the rows.
- The inner for loop enables you to tap into the elements in each row.
Here’s the corresponding output.
Output
2
3
7
8
How to Read Command-Line Arguments Using for Loop

As a developer, you should be comfortable running Python scripts from the command line and using command-line arguments to interact with your script.
You can use Python’s built-in modules such as sys and argparse to parse and read command-line arguments.
In this section, we’ll go over how to use the sys
module and use a for
loop—to loop through the list of command-line arguments.
In the sys module, sys.argv
is the list of command-line arguments that you pass in. So you can loop through sys.argv
just the way you’d loop through any Python list.
# main.py
import sys
for arg in sys.argv:
print(arg)
You can now run the program from the command line, as shown below.
$ python main.py Hello Python3
main.py
Hello
Python3
By default, the name of the module is the first argument and is at index zero in sys.argv
.
If you want to access the indices and the corresponding arguments, you can use the range()
function.
# main.py
import sys
for i in range(len(sys.argv)):
print(f"arg{i} is {sys.argv[i]}")
▶️ Next, re-run main.py.
$ python main.py Hello Python3
arg0 is main.py
arg1 is Hello
arg2 is Python3
Suppose you’d like to parse and process the arguments other than the module name. You can set the start value to 1, as in the code cell below.
# main.py
import sys
for i in range(1,len(sys.argv)):
print(f"arg{i} is {sys.argv[i]}")
$ python main.py Hello Python3
arg1 is Hello
arg2 is Python3

Putting it all together, the main.py file contains the following code.
# main.py
import sys
print("\nPrinting all command-line arguments...")
for arg in sys.argv:
print(arg)
print("\nPrinting all command-line arguments with index...")
for i in range(len(sys.argv)):
print(f"arg{i} is {sys.argv[i]}")
print("\nPrinting command-line arguments except arg0: module_name...")
for i in range(1,len(sys.argv)):
print(f"arg{i} is {sys.argv[i]}")
Here is the output when you run the module.
$ python main.py Hello Python3
Printing all command-line arguments...
main.py
Hello
Python3
Printing all command-line arguments with index...
arg0 is main.py
arg1 is Hello
arg2 is Python3
Printing command-line arguments except arg0: module_name...
arg1 is Hello
arg2 is Python3
How to Use break Statement Inside for Loop

Like other programming languages, Python also supports the use of loop control statements break
and continue
. These statements can help alter the control flow in loops, based on some conditions. Let’s see how to use them inside a for loop.
The break
the statement can be used to break out of a loop when a specific condition is True
.
We want to write a program to do the following:
- Fix
k
, the number of inputs. - Use a
for
loop to read in user inputs—one digit at a time, and sum up the non-negative numbers (greater than or equal to zero). - This process should continue so long as the user enters non-negative numbers.
- When the user enters a negative number, exit the loop and print out the sum.
Here’s the code that performs the above task.
k= 5
sum = 0
for i in range(k):
num = int(input("\nEnter a number: "))
if num<0:
break # exit loop when num < 0
sum += num
print(sum)
If the user enters a number less than zero, the control breaks out of the for loop to the first statement after the loop.
Enter a number: 2
Enter a number: 3
Enter a number: 5
Enter a number: -1
10
How to Use continue Statement Inside for Loop
The continue
statement can be used to skip certain iterations depending on a specific condition.
Let’s use the same examples in the previous section.
- Read in user input and compute sum of non-negative numbers.
- If the user enters a negative number, skip that iteration proceed to the next iteration ,and read in the next number.
k = 5
sum = 0
for i in range(k):
num = int(input("\nEnter a number: "))
if num<0:
continue
sum += num
print(sum)
Here is a sample output.
Enter a number: 2
Enter a number: 3
Enter a number: 5
Enter a number: -1
Enter a number: 3
13
The fourth number is -1, which is negative. However, this time the for loop goes on until we reach the specified number of inputs, and ignores negative inputs. Essentially, it returns the sum of all non-negative numbers from the k input numbers.
Can You Run Into an Infinite for Loop in Python?

In all the examples and use cases that we’ve discussed thus far, we never ran into the problem of an infinite for loop. But can we have an infinite for loop in Python?
Consider the following function double()
.
def double(x = 1):
return x*2
- When you call the function
double()
without specifying the value ofx
, the default value of 1 is used. - When you specify a value for
x
in the function call, that value is used.
double()
# Returns: 2
double(20)
# Returns: 40
In Python, the iter() function returns an iterator object. You can use next(iter-obj)
to iterate through the sequence and access subsequent items.
– Consider a callable-object and a value, sentinel.
–
iter(callable-object, sentinel)
can be used to perform iteration until the return value from thecallable-object
is equal tosentinel
.
Do you see why we can have an infinite for loop in this case?

Well, you have a callable-object
and a sentinel
value. If the return value from the callable is never equal to the sentinel, then the loop goes on forever!
Let’s use the above function double
as the callable, and set the sentinel value to 0.
Note: Mention the name of the function double
, not the function call double()
.
As the return value from the function double
is always 2 and is never equal to 0, we have an infinite loop!
▶️ Try running the following code cell. It’s infinite for loop, and you’ll have to force stop the program.
for _ in iter(double,0):
print("Running...")

Python For Loops: Practice Questions
#1. Use for loop to print out all even numbers in the range 0 to 20.
Hint: Use range()
function with the correct step
value.
#2. Print out all even numbers from 20 down to 0.
Hint: Use negative value for the step
parameter in the range()
function.
#3. Create a three-dimensional NumPy array.
Hint: Use for loop and nested for loops as needed to access the rows and individual entries in the array.
Wrapping Up
Here’s a summary of what you have learned in this tutorial.
- The syntax to use the Python for loop along with range() and enumerate() functions
- Using for loops to loop through lists, arrays, and strings, and read in command-line arguments
- Using loop control statements: break to break out of the loop and continue statement to skip certain iterations—based on conditions—inside for loops
- Understanding the possibility of infinite for loops in Python
Next, learn how to use the split() method in Python.
-
Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more