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) {

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

# Python style foreach loop
for city in cities:

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.

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

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright Β© Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap