Python foreach equivalent

Python foreach equivalent

Sure. A for loop.

for f in pets:
    print f

Like this:

for pet in pets :

In fact, Python only has foreach style for loops.

Python foreach equivalent

Its also interesting to observe this

To iterate over the indices of a sequence, you can combine range() and len() as follows:

a = [Mary, had, a, little, lamb]
for i in range(len(a)):
  print(i, a[i])


0 Mary
1 had
2 a
3 little
4 lamb

Edit#1: Alternate way:

When looping through a sequence, the position index and corresponding value can be retrieved at the same
time using the enumerate() function.

for i, v in enumerate([tic, tac, toe]):
  print(i, v)


0 tic
1 tac
2 toe

Leave a Reply

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