Is Foreach In Python Available?

foreach in python

Foreach loop is available in PHP, Java, JavaScript, etc. If you’re starting with Python, you might wonder if foreach in Python is available? Or if there is a loop similar to foreach. So in this article, we will help you better understand.

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.

Use 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:

websites = ['', '', '', '']
forEach(websites, print)


Loop through with the index

If you need to work with the index in For Loop, use range() and len() functions. These 2 functions are used a lot in Python loops. See the sample code below to know how to use them.

websites = ['', '', '', '']

# Combine range() and len() in the for loop
for i in range(len(websites)):
    print(i, websites[i])



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 = ['', '', '', '']

# Uppercase the element of the websites
[print(website.upper()) for website in websites]




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:

Leave a Reply

Your email address will not be published. Required fields are marked *