Is Python foreach loop available?

The foreach is a type of loop that is generally available in different programming languages like C#, PHP etc. The purpose of foreach loop is to iterate through arrays or collections easily.

Then why Python does not support it? Well, there is another handy way of doing this job quite easily. You can say doing foreach in Pythonic way.

How to use “foreach” in Python?

As the term foreach suggests, foreach loop entertains each item of the array or iterator (list, range, tuple etc.). The same can be achieved by using the for..in loop in Python as in the example below:

#A demo of "foreach loop"



for x in range(10,40,2):

    print (x)

Python foreach

You can see, a range is used in the for loop with “in” operator.

A “Foreach” example using a list

For this example, a list is created with five items. After that, a for..in loop is used to iterate through the list items. The print function displays each item of the list as shown below:

# A foreach demo with list



str_foreach = ['foreach','loop','Pythonic','way']



for lst_item in str_foreach:

    print (lst_item)

foreach list

A demo of foreach loop with dictionary

The dictionary is created by using the key/value pairs. The for..in also enables you to iterate through each element of the dictionary where you may use both keys and values. Have a look:

#A demo foreach with dictionary

salary_dir = {'Haynes': '$5000','Ali': '$5500', 'Areeb':'$3500'}



for name, sal in salary_dir.items():



    print ("The Salary of %s = %s" % (name, sal))

foreach dictionary

You can see, two variables are used in the for loop before in clause for the key and value which is followed by the in operator. Finally, the dictionary name is given with it item() method.

The print statement is used to display the name and salary in the dictionary.

Using a set example in for each

For this example, a set is created and for..in loop is used to iterate through its items. FYI, a set is created by using the curly braces {} and separating each item by commas:

set_foreach = {3, 5, 7, 'a', 'b', 'c'}



for items in set_foreach:



    print (items)

foreach set

Iterating through a string object using “foreach”

The final example is iterating through a string object.

str_foreach = "Python"

for s in str_foreach:

    print (s)

foreach string

You see, how simple it is to even go through the string object using “foreach Pythonic way”.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!