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 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)
output
0 tic
1 tac
2 toe
For an updated answer you can build a forEach
function in Python easily:
def forEach(list, function):
for i, v in enumerate(list):
function(v, i, list)
You could also adapt this to map
, reduce
, filter
, and any other array functions from other languages or precedence you'd want to bring over. For loops are fast enough, but the boiler plate is longer than forEach
or the other functions. You could also extend list to have these functions with a local pointer to a class so you could call them directly on lists as well.
While the answers above are valid, if you are iterating over a dict {key:value} it this is the approach I like to use:
for key, value in Dictionary.items():
print(key, value)
Therefore, if I wanted to do something like stringify all keys and values in my dictionary, I would do this:
stringified_dictionary = {}
for key, value in Dictionary.items():
stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary
This avoids any mutation issues when applying this type of iteration, which can cause erratic behavior (sometimes) in my experience.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With