Python Foreach - How to Implement ?
Last Updated :
26 Apr, 2025
Foreach loop is a convenient way to iterate over elements in a collection, such as an array or list. Python, however, does not have a dedicated foreach loop like some other languages (e.g., PHP or JavaScript). We will explore different ways to implement a foreach-like loop in Python, along with examples to illustrate their usage.
Using the For Loop using Python 'in'
The most straightforward way to iterate over elements in a collection in Python is by using the for loop. This loop automatically iterates over each item in the collection, providing a clean and readable way to access each element.
Python
a = [1, 2, 3, 4, 5]
for n in a:
print(n)
Example: Let's consider a practical example where we have a list of dictionaries representing students, and we want to print each student's name and grade.
Python
s = [
{"name": "RAM", "grade": "A"},
{"name": "SITA", "grade": "B"},
{"name": "GITA", "grade": "C"}
]
for student in s:
print(f"Name: {student['name']}, Grade: {student['grade']}")
OutputName: RAM, Grade: A
Name: SITA, Grade: B
Name: GITA, Grade: C
Explanation: This code iterates through a list of dictionaries (s), where each dictionary contains a student's name and grade. For each student, it prints their name and grade using an f-string.
Using the map Function
The map function in Python applies a specified function to each item in an iterable (such as a list) and returns a map object (which is an iterator). This approach is particularly useful when you want to apply a transformation or function to each element in the collection.
Python
def square(n):
return n * n
a = [1, 2, 3, 4, 5]
sn = map(square, a)
for n in sn:
print(n)
Explanation: map(square, a) applies the square() function to every element in the list a and returns a map object (sn), which is an iterable.
Using List Comprehensions
List comprehensions provide a concise way to create lists and can also be used to iterate over elements in a collection. While list comprehensions are typically used for creating new lists, they can also be utilized to perform actions on each element.
Python
a = [1, 2, 3, 4, 5]
[print(num) for num in a]
The itertools module in Python provides a variety of tools for working with iterators. One of the functions, starmap, can be used to apply a function to the elements of an iterable. This is particularly useful for iterating over elements that are tuples or pairs.
Python
from itertools import starmap
p = [(1, 2), (3, 4), (5, 6)]
def add(a, b):
return a + b
r = starmap(add, p)
for res in r:
print(res)
Explanation: This code uses itertools.starmap() to apply the add() function to each tuple in the list p. The starmap() function unpacks each tuple in p and passes the elements as arguments to the add() function.
Similar Reads
How To Do Pagination In Python In this article, we'll walk you through the steps of setting up pagination in Python. We'll explain each step clearly and straightforwardly. To help you understand the idea of pagination in Python, we'll show you how to create a pagination system using the Tkinter library. We'll start by explaining
5 min read
How to Initialize a List in Python Python List is an ordered collections on items, where we can insert, modify and delete the values. Let's first see how to initialize the list in Python with help of different examples. Initialize list using square brackets []Using [] we can initialize an empty list or list with some items. Python# I
2 min read
How to Call Multiple Functions in Python In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, weâll explore various ways we can call multiple functions in Python.The most straightforward way to call multiple functions is by executing them one after a
3 min read
How to call a function in Python Python is an object-oriented language and it uses functions to reduce the repetition of the code. In this article, we will get to know what are parts, How to Create processes, and how to call them.In Python, there is a reserved keyword "def" which we use to define a function in Python, and after "de
5 min read
How to Create a List of N-Lists in Python In Python, we can have a list of many different kinds, including strings, numbers, and more. Python also allows us to create a nested list, often known as a two-dimensional list, which is a list within a list. Here we will cover different approaches to creating a list of n-lists in Python. The diffe
3 min read
How to Build a basic Iterator in Python? Iterators are a fundamental concept in Python, allowing you to traverse through all the elements in a collection, such as lists or tuples. While Python provides built-in iterators, there are times when you might need to create your own custom iterator to handle more complex data structures or operat
4 min read
How to create a list of object in Python class In Python, creating a list of objects involves storing instances of a class in a list, which allows for easy access, modification and iteration. For example, with a Geeks class having attributes name and roll, you can efficiently manage multiple objects in a list. Let's explore different methods to
3 min read
How to Access Index using for Loop - Python When iterating through a list, string, or array in Python, it's often useful to access both the element and its index at the same time. Python offers several simple ways to achieve this within a for loop. In this article, we'll explore different methods to access indices while looping over a sequenc
2 min read
Implementation of Dynamic Array in Python What is a dynamic array? A dynamic array is similar to an array, but with the difference that its size can be dynamically modified at runtime. Don't need to specify how much large an array beforehand. The elements of an array occupy a contiguous block of memory, and once created, its size cannot be
4 min read
Comprehensions in Python Comprehensions in Python provide a concise and efficient way to create new sequences from existing ones. They enhance code readability and reduce the need for lengthy loops. Python supports four types of comprehensions:List ComprehensionsDictionary ComprehensionsSet ComprehensionsGenerator Comprehen
3 min read