Hit enter after type your search item

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:

See online demo and code


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:

See online demo and code


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:

See online demo and code


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:

See online demo and code


foreach set

Iterating through a string object using “foreach”

The final example is iterating through a string object.

See online demo and code


foreach string

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

This div height required for enabling the sticky sidebar