The Wayback Machine - https://web.archive.org/web/20240821211907/https://www.geeksforgeeks.org/python-foreach-how-to-program-in-python/
Open In App

Python Foreach: How to Program in Python

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In many programming languages, the 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). In this article, we will explore different ways to implement a foreach-like loop in Python, along with examples to illustrate their usage.

Different Ways to Implement Foreach in Python

1. 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
numbers = [1, 2, 3, 4, 5]

for number in numbers:
    print(number)

Output
1
2
3
4
5

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
students = [
    {"name": "RAM", "grade": "A"},
    {"name": "SITA", "grade": "B"},
    {"name": "GITA", "grade": "C"}
]

for student in students:
    print(f"Name: {student['name']}, Grade: {student['grade']}")

Output

Name: RAM, Grade: AName: SITA, Grade: BName: GITA, Grade: C

2. 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(number):
    return number * number

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(square, numbers)

for number in squared_numbers:
    print(number)

Output

1
4
9
16
25

3. 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
numbers = [1, 2, 3, 4, 5]

[print(number) for number in numbers]

Output
1
2
3
4
5

4. Using the itertools Module

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

pairs = [(1, 2), (3, 4), (5, 6)]

def add(a, b):
    return a + b

results = starmap(add, pairs)

for result in results:
    print(result)

Output
3
7
11

Conclusion

In Python, there are multiple ways to achieve the functionality of a foreach loop, each with its own advantages. Whether you use a simple for loop, the map function, list comprehensions, the enumerate function, or tools from the itertools module, Python provides flexible and powerful options for iterating over collections. Understanding these methods will enhance your ability to write clean, efficient, and readable Python code.



Previous Article
Next Article

Similar Reads

PySpark dataframe foreach to fill a list
In this article, we are going to learn how to make a list of rows in Pyspark dataframe using foreach using Pyspark in Python. PySpark is a powerful open-source library for working on large datasets in the Python programming language. It is designed for distributed computing and it is commonly used for data manipulation and analysis tasks. By using
3 min read
Hello World Program : First program while learning Programming
In this article, I'll show you how to create your first Hello World computer program in various languages. Along with the program, comments are provided to help you better understand the terms and keywords used in theLearning program. Programming can be simplified as follows: Write the program in a text editor and save it with the correct extension
6 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
OpenCV Python Program to blur an image
Note: This post contains codes that cannot be run using an online compiler. Please make sure that you have Python 2.7 and cv2 module installed before trying to run the program on your system. Hi everyone! I read a brilliant work by Aditya Prakash – OpenCV C++ Program to blur an image, so I decided to come up with something similar but this time in
2 min read
Opencv Python program for Face Detection
The objective of the program given is to detect object of interest(face) in real time and to keep tracking of the same object.This is a simple example of how to detect face in Python. You can try to use training samples of any other object of your choice to be detected by training the classifier on required objects. Here is the steps to download th
2 min read
Python program to convert time from 12 hour to 24 hour format
Given a time in 12-hour AM/PM format, convert it to military (24-hour) time. Note : Midnight is 12:00:00 AM on a 12-hour clock and 00:00:00 on a 24-hour clock. Noon is 12:00:00 PM on 12-hour clock and 12:00:00 on 24-hour clock. Examples : Input : 11:21:30 PMOutput : 23:21:30Input : 12:12:20 AMOutput : 00:12:20How to Convert AM/PM to 24 Hour Time Wh
3 min read
Python program to convert XML to Dictionary
In this article, we will discuss how to convert an XML to a dictionary using Python. Modules Usedxmltodict: It is a Python module that makes working with XML feel like you are working with [JSON]. Run the following command in the terminal to install the module. Syntax: pip install xmltodict pprint: The pprint module provides a capability to “pretty
2 min read
Python Program to Print Hello World
"Hello, World!" is often the first program that programmers learn to write when they start learning a new programming language. It's a simple program that prints the phrase "Hello, World!" to the console or output window. Python is a high-level, interpreted programming language that is known for its readability and ease of use. Python is often used
2 min read
Python Program to Check if Two Strings are Anagram
Question: Given two strings s1 and s2, check if both the strings are anagrams of each other. Examples: Input : s1 = "listen" s2 = "silent" Output : The strings are anagrams. Input : s1 = "dad" s2 = "bad" Output : The strings aren't anagrams.Solution:Method #1 : Using sorted() function Python provides a inbuilt function sorted() which does not modif
5 min read
Program to print all distinct elements of a given integer array in Python | Ordered Dictionary
Given an integer array, print all distinct elements in array. The given array may contain duplicates and the output should print every element only once. The given array is not sorted. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45} Output: 12, 10, 9, 45, 2 Input: arr[] = {1, 2, 3, 4, 5} Output: 1, 2, 3, 4, 5 Input: arr[] = {1, 1, 1, 1, 1}
2 min read
Python program to print checkerboard pattern of nxn using numpy
Given n, print the checkerboard pattern for a n x n matrix Checkerboard Pattern for n = 8: It consists of n * n squares of alternating 0 for white and 1 for black. We can do the same using nested for loops and some if conditions, but using Python's numpy library, we can import a 2-D matrix and get the checkerboard pattern using slicing. W2'll be us
3 min read
Python program to check the validity of a Password
In this program, we will be taking a password as a combination of alphanumeric characters along with special characters, and checking whether the password is valid or not with the help of a few conditions. Primary conditions for password validation: Minimum 8 characters.The alphabet must be between [a-z]At least one alphabet should be of Upper Case
3 min read
Python List Equality | Program to check if two given matrices are identical
We are given two square matrices of same order. Check if two given matrices are identical. Examples: Input : A = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] Output: Matrices are identical We have existing solution for this problem please refer C Program to check if two give
3 min read
Python Program to Split the Even and Odd elements into two different lists
In this program, a list is accepted with a mixture of odd and even elements and based on whether the element is even or odd, it is Split the Even and Odd elements using Python. Examples Input: [8, 12, 15, 9, 3, 11, 26, 23] Output: Even lists: [8, 12, 26] Odd lists: [15, 9, 3, 11, 23] Input: [2, 5, 13, 17, 51, 62, 73, 84, 95] Output: Even lists: [2,
2 min read
Python | Program to print duplicates from a list of integers
Given a list of integers with duplicate elements in it. The task is to generate another list, which contains only the duplicate elements. In simple words, the new list should contain elements that appear as more than one. Examples: Input : list = [10, 20, 30, 20, 20, 30, 40, 50, -20, 60, 60, -20, -20] Output : output_list = [20, 30, -20, 60]Input :
5 min read
Python program to extract Email-id from URL text file
Prerequisite : Pattern Matching with Python Regex Given the URL text-file, the task is to extract all the email-ids from that text file and print the urllib.request library can be used to handle all the URL related work. Example : Input : Hello This is Geeksforgeeks review-team@geeksforgeeks.org review-team@geeksforgeeks.org GfG is a portal for gee
1 min read
Python program to count upper and lower case characters without using inbuilt functions
Given a string that contains both upper and lower case characters in it. The task is to count a number of upper and lower case characters in it. Examples :Input : Introduction to Python Output : Lower Case characters : 18 Upper case characters : 2 Input : Welcome to GeeksforGeeks Output : Lower Case characters : 19 Upper case characters: 3Method 1:
3 min read
Python | Basic Program Crash Debugging
If the program is crashing with an exception, running the program as python3 -i can be a useful tool for simply looking around. The -i option starts an interactive shell as soon as a program terminates. From there, the environment can be explored. Code #1: Given the code # abc.py def func(n): return n + 10 func('Hello') Code #2: Running python3 -i
2 min read
Python | Program to implement simple FLAMES game
Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame. FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately
6 min read
Python Program to Print Numbers in an Interval
Given a range of numbers, find all the numbers between them. Example: Input : l = 2, u = 5Output : 2 3 4 5 Input : l = 10, u = 20 Output : 10 11 12 13 14 15 16 17 18 19 20 The idea is to use range function in Python. C/C++ Code # Python program to print all the numbers within an interval l = 10 u = 20 for num in range(l, u + 1): print(num) Output:1
2 min read
Python program to create Bankaccount class with deposit, withdraw function
Prerequisite: Object Oriented Programming in PythonLet's write a simple Python program using OOP concept to perform some simple bank operations like deposit and withdrawal of money.First of all, define class Bankacccount. This step is followed by defining a function using __init__. It is run as soon as an object of a class is instantiated. This __i
2 min read
Python Program to Convert a list of multiple integers into a single integer
Given a list of integers, write a Python program to convert the given list into a single integer. Examples: Input : [1, 2, 3] Output : 123 Input : [55, 32, 890] Output : 5532890 There are multiple approaches possible to convert the given list into a single integer. Let's see each one by one. Approach #1 : Naive Method Simply iterate each element in
4 min read
Python Program to Check if String is Empty or Not
Python strings are immutable and have more complex handling when discussing their operations. Note that a string with spaces is actually an empty string but has a non-zero size. This article also discussed that problem and the solution to it. Let's see different methods of Check if String is Empty Python. Example Input:[" "]Output: YesExplanation:
8 min read
Python program to find middle of a linked list using one traversal
Given a singly linked list, find the middle of the linked list. Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. Method 1: Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2 and return the n
5 min read
Python program to create a dictionary from a string
Dictionary in python is a very useful data structure and at many times we see problems regarding converting a string to a dictionary. So, let us discuss how we can tackle this problem. Method # 1: Using eval() If we get a string input which completely resembles a dictionary object(if the string looks like dictionary as in python) then we can easily
3 min read
Python | OpenCV program to read and save an Image
OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision. This is cross-platform library, it provides functions that are used in multiple languages. Coming to image processing, OpenCV enables us to perform multiple operations on image, but in order to do that we need to read an image file
2 min read
Python | Program to download complete Youtube playlist
Python is a multi-purpose programming language and is widely used for scripting small tasks. Let's see how to make your own Youtube Playlist Downloader using Python. Though there are many software available in the market but making your own serving that purpose is quite a learning and impressive as well. Modules needed: BeautifulSoup bs4PyQt5PyQtWe
3 min read
Python | Timing and Profiling the program
Problems - To find where the program spends its time and make timing measurements. To simply time the whole program, it’s usually easy enough to use something like the Unix time command as shown below. Code #1 : Command to time the whole program bash % time python3 someprogram.py real 0m13.937s user 0m12.162s sys 0m0.098s bash % On the other extrem
2 min read
Python | Making program run faster
As we know, Python programming language is a bit slow and the target is to speed it up without the assistance of more extreme solutions, such as C extensions or a just-in-time (JIT) compiler.While the first rule of optimization might be to "not do it", the second rule is almost certainly "don’t optimize the unimportant." To that end, if the program
8 min read
Python | How to time the program
This article aims to show how to calculate the time it takes to perform various tasks. A simple solution to it is to use time module. This module contains various time-related functions. Also it's very useful to put a higher-level interface over these functions and use them as a stop-watch as explained in the code below - Code #1 : C/C++ Code # Usi
2 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg