Python foreach equivalent [duplicate] Python foreach equivalent [duplicate] python python

Python foreach equivalent [duplicate]


Sure. A for loop.

for f in pets:    print f


Like this:

for pet in pets :  print(pet)

In fact, Python only has foreach style for loops.


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

output

0 Mary1 had2 a3 little4 lamb

Edit#1: Alternate way:

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

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

output

0 tic1 tac2 toe


matomo