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.
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.).
#A demo of "foreach loop" for x in range(10,40,2): print (x)
You can see that 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)
Output:
loop
Pythonic
way
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))
Result:
The Salary of Ali = $5500
The Salary of Areeb = $3500
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)
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)
Output:
y
t
h
o
n
You see, how simple it is to even go through the string object using “foreach Pythonic way”.