What is foreach?
Foreach in C#, PHP, … is an iterative construct that allows us to iterate over an array or a set.
Some features of foreach:
- foreach traverses the array without an index.
- foreach iterates through the elements in the array.
- foreach is only used to traverse iterable objects and cannot traverse other data types.
We’ll find it convenient if we’ve worked with foreach in another language.
But the most important thing in this article is that foreach is not included in Python. It means that Python does not support keywords like forEach or foreach.
So, what should we use instead of foreach in Python?
You can replace foreach with
for … in … aka For Loop in Python. Not only that, there are so many other ways to replace foreach. We will introduce you right now.
for … in … loop
Before reading on, you can read more about the syntax of For Loop in Python here.
There is no foreach in Python, but if you want, you can create a foreach function yourself using
for ... in ... like this:
def forEach(iterable, function): # Using for ... in ... for x in iterable: function(x) websites = ['learnshareit.com', 'facebook.com', 'twitter.com', 'google.com'] forEach(websites, print)
learnshareit.com facebook.com twitter.com google.com
Loop through with the index
websites = ['learnshareit.com', 'facebook.com', 'twitter.com', 'google.com'] # Combine range() and len() in the for loop for i in range(len(websites)): print(i, websites[i])
0 learnshareit.com 1 facebook.com 2 twitter.com 3 google.com
Use List Comprehension
List Comprehension is a quick way to filter or edit a list. It helps you write more concise and readable code.
We can use List Comprehension to quickly traverse a list and work with each element of the list. Like this:
websites = ['learnshareit.com', 'facebook.com', 'twitter.com', 'google.com'] # Uppercase the element of the websites [print(website.upper()) for website in websites]
LEARNSHAREIT.COM FACEBOOK.COM TWITTER.COM GOOGLE.COM
As mentioned at the beginning of the article, there is no foreach in Python. However, there are shorter and easier-to-use ways than foreach in other languages to iterate over an object.
Hope the knowledge in the article will help you become a Python developer in the future.
Have a nice day!
Maybe you are interested:
Name of the university: HCMUE