
- Python Basics
- Python - Home
- Python - Overview
- Python - History
- Python - Features
- Python vs C++
- Python - Hello World Program
- Python - Application Areas
- Python - Interpreter
- Python - Environment Setup
- Python - Virtual Environment
- Python - Basic Syntax
- Python - Variables
- Python - Data Types
- Python - Type Casting
- Python - Unicode System
- Python - Literals
- Python - Operators
- Python - Arithmetic Operators
- Python - Assignment Operators
- Python - Augmented Addition Operator (+=)
- Python - Comparison Operators
- Python - Logical Operators
- Python - Bitwise Operators
- Python - Membership Operators
- Python - Identity Operators
- Python - Comments
- Python - User Input
- Python - Numbers
- Python - Booleans
- Python Control Statements
- Python - Control Flow
- Python - Decision Making
- Python - If else
- Python - Match-Case Statement
- Python - The for Loop
- Python - The for-else Loop
- Python - While Loops
- Python - The break Statement
- Python - The continue Statement
- Python - The pass Statement
- Python Functions & Modules
- Python - Functions
- Python - Default Arguments
- Python - Keyword Arguments
- Python - Keyword-Only Arguments
- Python - Positional Arguments
- Python - Positional-Only Arguments
- Python - Arbitrary Arguments
- Python - Variables Scope
- Python - Function Annotations
- Python - Modules
- Python - Built in Functions
- Python Strings
- Python - Strings
- Python - Slicing Strings
- Python - Modify Strings
- Python - String Concatenation
- Python - String Formatting
- Python - Escape Characters
- Python - String Methods
- Python - String Exercises
- Python Lists
- Python - Lists
- Python - Access List Items
- Python - Change List Items
- Python - Add List Items
- Python - Remove List Items
- Python - Loop Lists
- Python - List Comprehension
- Python - Sort Lists
- Python - Copy Lists
- Python - Join Lists
- Python - List Methods
- Python - List Exercises
- Python Tuples
- Python - Tuples
- Python - Access Tuple Items
- Python - Update Tuples
- Python - Unpack Tuples
- Python - Loop Tuples
- Python - Join Tuples
- Python - Tuple Methods
- Python - Tuple Exercises
- Python Sets
- Python - Sets
- Python - Access Set Items
- Python - Add Set Items
- Python - Remove Set Items
- Python - Loop Sets
- Python - Join Sets
- Python - Copy Sets
- Python - Set Operators
- Python - Set Methods
- Python - Set Exercises
- Python Dictionaries
- Python - Dictionaries
- Python - Access Dictionary Items
- Python - Change Dictionary Items
- Python - Add Dictionary Items
- Python - Remove Dictionary Items
- Python - Dictionary View Objects
- Python - Loop Dictionaries
- Python - Copy Dictionaries
- Python - Nested Dictionaries
- Python - Dictionary Methods
- Python - Dictionary Exercises
- Python Arrays
- Python - Arrays
- Python - Access Array Items
- Python - Add Array Items
- Python - Remove Array Items
- Python - Loop Arrays
- Python - Copy Arrays
- Python - Reverse Arrays
- Python - Sort Arrays
- Python - Join Arrays
- Python - Array Methods
- Python - Array Exercises
- Python File Handling
- Python - File Handling
- Python - Write to File
- Python - Read Files
- Python - Renaming and Deleting Files
- Python - Directories
- Python - File Methods
- Python - OS File/Directory Methods
- Object Oriented Programming
- Python - OOPs Concepts
- Python - Object & Classes
- Python - Class Attributes
- Python - Class Methods
- Python - Static Methods
- Python - Constructors
- Python - Access Modifiers
- Python - Inheritance
- Python - Polymorphism
- Python - Method Overriding
- Python - Method Overloading
- Python - Dynamic Binding
- Python - Dynamic Typing
- Python - Abstraction
- Python - Encapsulation
- Python - Interfaces
- Python - Packages
- Python - Inner Classes
- Python - Anonymous Class and Objects
- Python - Singleton Class
- Python - Wrapper Classes
- Python - Enums
- Python - Reflection
- Python Errors & Exceptions
- Python - Syntax Errors
- Python - Exceptions
- Python - try-except Block
- Python - try-finally Block
- Python - Raising Exceptions
- Python - Exception Chaining
- Python - Nested try Block
- Python - User-defined Exception
- Python - Logging
- Python - Assertions
- Python - Built-in Exceptions
- Python Multithreading
- Python - Multithreading
- Python - Thread Life Cycle
- Python - Creating a Thread
- Python - Starting a Thread
- Python - Joining Threads
- Python - Naming Thread
- Python - Thread Scheduling
- Python - Thread Pools
- Python - Main Thread
- Python - Thread Priority
- Python - Daemon Threads
- Python - Synchronizing Threads
- Python Synchronization
- Python - Inter-thread Communication
- Python - Thread Deadlock
- Python - Interrupting a Thread
- Python Networking
- Python - Networking
- Python - Socket Programming
- Python - URL Processing
- Python - Generics
- Python Miscellenous
- Python - Date & Time
- Python - Maths
- Python - Iterators
- Python - Generators
- Python - Closures
- Python - Decorators
- Python - Recursion
- Python - Reg Expressions
- Python - PIP
- Python - Database Access
- Python - Weak References
- Python - Serialization
- Python - Templating
- Python - Output Formatting
- Python - Performance Measurement
- Python - Data Compression
- Python - CGI Programming
- Python - XML Processing
- Python - GUI Programming
- Python - Command-Line Arguments
- Python - Docstrings
- Python - JSON
- Python - Sending Email
- Python - Further Extensions
- Python - Tools/Utilities
- Python - GUIs
- Python Questions and Answers
- Python - Programming Examples
- Python - Quick Guide
- Python - Useful Resources
- Python - Discussion
Python - The for Loop
The for loop in Python has the ability to iterate over the items of any sequence, such as a list or a string.
Syntax
for iterating_var in sequence: statements(s)
If a sequence contains an expression list, it is evaluated first. Then, the first item (at 0th index) in the sequence is assigned to the iterating variable iterating_var.
Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statement(s) block is executed until the entire sequence is exhausted.
The following flow diagram illustrates the working of for loop −

Since the loop is executed for each member element in a sequence, there is no need for explicit verification of Boolean expression controlling the loop (as in while loop).
The sequence objects such as list, tuple or string are called iterables, as the for loop iterates through the collection. Any iterator object can be iterated by the for loop.
The view objects returned by items(), keys() and values() methods of dictionary are also iterables, hence we can run a for loop with them.
Pythonâs built-in range() function returns an iterator object that streams a sequence of numbers. We can run a for loop with range.
Using "for" with a String
A string is a sequence of Unicode letters, each having a positional index. The following example compares each character and displays if it is not a vowel (âaâ, âeâ, âIâ, âoâ or âuâ)
Example
zen = ''' Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. ''' for char in zen: if char not in 'aeiou': print (char, end='')
Output
On executing, this code will produce the following output −
Btfl s bttr thn gly. Explct s bttr thn mplct. Smpl s bttr thn cmplx. Cmplx s bttr thn cmplctd.
Using "for" with a Tuple
Pythonâs tuple object is also an indexed sequence, and hence we can traverse its items with a for loop.
Example
In the following example, the for loop traverses a tuple containing integers and returns the total of all numbers.
numbers = (34,54,67,21,78,97,45,44,80,19) total = 0 for num in numbers: total+=num print ("Total =", total)
Output
On executing, this code will produce the following output −
Total = 539
Using "for" with a List
Pythonâs list object is also an indexed sequence, and hence we can traverse its items with a for loop.
Example
In the following example, the for loop traverses a list containing integers and prints only those which are divisible by 2.
numbers = [34,54,67,21,78,97,45,44,80,19] total = 0 for num in numbers: if num%2 == 0: print (num)
Output
On executing, this code will produce the following output −
34 54 78 44 80
Using "for" with a Range Object
Pythonâs buil-in range() function returns a range object. Pythonâs range object is an iterator which generates an integer with each iteration. The object contains integrrs from start to stop, separated by step parameter.
Syntax
The range() function has the following syntax −
range(start, stop, step)
Parameters
Start − Starting value of the range. Optional. Default is 0
Stop − The range goes upto stop-1
Step − Integers in the range increment by the step value. Option, default is 1.
Return Value
The range() function returns a range object. It can be parsed to a list sequence.
Example
numbers = range(5) ''' start is 0 by default, step is 1 by default, range generated from 0 to 4 ''' print (list(numbers)) # step is 1 by default, range generated from 10 to 19 numbers = range(10,20) print (list(numbers)) # range generated from 1 to 10 increment by step of 2 numbers = range(1, 10, 2) print (list(numbers))
Output
On executing, this code will produce the following output −
[0, 1, 2, 3, 4] [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] [1, 3, 5, 7, 9]
Example
Once we obtain the range, we can use the for loop with it.
for num in range(5): print (num, end=' ') print() for num in range(10,20): print (num, end=' ') print() for num in range(1, 10, 2): print (num, end=' ')
Output
On executing, this code will produce the following output −
0 1 2 3 4 10 11 12 13 14 15 16 17 18 19 1 3 5 7 9
Example: Factorial of a Number
Factorial is a product of all numbers from 1 to that number say n. It can also be defined as product of 1, 2, up to n.
Factorial of a number n! = 1 * 2 * . . . . . * n
We use the range() function to get the sequence of numbers from 1 to n-1 and perform cumumulative multplication to get the factorial value.
fact=1 N = 5 for x in range(1, N+1): fact=fact*x print ("factorial of {} is {}".format(N, fact))
Output
On executing, this code will produce the following output −
factorial of 5 is 120
In the above program, change the value of N to obtain factorial value of different numbers.
Using "for" Loop with Sequence Index
To iterate over a sequence, we can obtain the list of indices using the range() function
Indices = range(len(sequence))
We can then form a for loop as follows:
numbers = [34,54,67,21,78] indices = range(len(numbers)) for index in indices: print ("index:",index, "number:",numbers[index])
On executing, this code will produce the following output −
index: 0 number: 34 index: 1 number: 54 index: 2 number: 67 index: 3 number: 21 index: 4 number: 78
Using "for" with Dictionaries
Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the items do not have a positional index. However, traversing a dictionary is still possible with different techniques.
Running a simple for loop over the dictionary object traverses the keys used in it.
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers: print (x)
On executing, this code will produce the following output −
10 20 30 40
Once we are able to get the key, its associated value can be easily accessed either by using square brackets operator or with the get() method. Take a look at the following example −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers: print (x,":",numbers[x])
It will produce the following output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
The items(), keys() and values() methods of dict class return the view objects dict_items, dict_keys and dict_values respectively. These objects are iterators, and hence we can run a for loop over them.
The dict_items object is a list of key-value tuples over which a for loop can be run as follows −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers.items(): print (x)
It will produce the following output −
(10, 'Ten') (20, 'Twenty') (30, 'Thirty') (40, 'Forty')
Here, "x" is the tuple element from the dict_items iterator. We can further unpack this tuple in two different variables. Check the following code −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x,y in numbers.items(): print (x,":", y)
It will produce the following output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty
Similarly, the collection of keys in dict_keys object can be iterated over. Take a look at the following example −
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} for x in numbers.keys(): print (x, ":", numbers[x])
It will produce the same output −
10 : Ten 20 : Twenty 30 : Thirty 40 : Forty