DEV Community

loading...
Cover image for Python Foreach for Beginners

Python Foreach for Beginners

courseprobe profile image Course Probe ・2 min read

In this mini tutorial, let’s take a look at some for each python loops for beginners or programmers comming to Python from other programming languages such as C or C++.

So, let’s say you have the following arrays in Python:

pets = ['cat', 'dog', 'fish']
marks = [ 5, 4, 3, 2, 1]
Enter fullscreen mode Exit fullscreen mode

You need to write some code which iterate over the arrays to do some work with the values on each position.

Example 1:

A for loop in Python.

for f in pets:
    print(f)
Enter fullscreen mode Exit fullscreen mode

Example 2:

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])
Enter fullscreen mode Exit fullscreen mode

output

0 Mary
1 had
2 a
3 little
4 lamb
Enter fullscreen mode Exit fullscreen mode

Example 3:

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)
Enter fullscreen mode Exit fullscreen mode

output

0 tic
1 tac
2 toe
Enter fullscreen mode Exit fullscreen mode

If you are a beginner learning Python programming, then I recommend taking a look at the below resources before continuing with the rest of the post.

Get the Book: Python Programming for beginners

Python for Beginners: Learn Python in One Day

Now let’s say you have mastered the basics of Python and you would like to build your own For Each function to loop over the arrays in your python code.

def forEach(list, function):
    for i, v in enumerate(list):
        function(v, i, list)
Enter fullscreen mode Exit fullscreen mode

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.

Example 4: Iterating over a dictionary in Python {key:value}

for key, value in Dictionary.items():
    print(key, value)
Enter fullscreen mode Exit fullscreen mode

If you want to stringify all the keys of the dictionary , you can go ahead and try:

stringified_dictionary = {}
for key, value in Dictionary.items():
    stringified_dictionary.update({str(key): str(value)})
return stringified_dictionary
Enter fullscreen mode Exit fullscreen mode

Example 5:

dictionary = {'a': 0, 'z': 25}
for index, (key, value) in enumerate(dictionary.items()):
     ## Code here ##
Enter fullscreen mode Exit fullscreen mode

Hope all of these examples are useful for you and you had fun implementing them in your code.

Reference links:


Other Dev Posts:

Discussion (2)

Collapse
highcenburg profile image
Vicente G. Reyes

I think you're missing a parenthesis on

for f in pets:
    print f
Enter fullscreen mode Exit fullscreen mode

When I ran it on Python 3.9, it returned

>>> for f in pets: print f
  File "<stdin>", line 1
    for f in pets: print f
                         ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(f)?
Enter fullscreen mode Exit fullscreen mode
Collapse
courseprobe profile image
Course Probe Author

Missing parentheses , great catch !!

Forem Open with the Forem app