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

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!