Java C# foreach loop equivalent in Python Programming


If you are looking for a foreach loop equivalent in Python, then you can look at the for loop.


Java Example:
String[] cities = {"London", "Paris", "New York", "Tokyo"};

//foreach loop
for (String city : cities) {
    System.out.println(city);
}

Python Example:
cities = ["London", "Paris", "New York", "Tokyo"]

# Python style foreach loop
for city in cities:
    print(city)


Reference Documentation:

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.

https://docs.python.org/3/tutorial/controlflow.html#for-statements
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap