Learning Management Platform for Written Tutorial Series.

Python 3 For loop - Iterate through iterables like a pro

Python 3 For loop - Iterate through iterables like a pro

Python For Loop

In this lesson, we will look at how we can iterate through a collection of items such as and how we can also execute a block of code for a predefined number of times. We will be looking at the for loop in python.

Topics to be covered

We will cover the following topics in this lesson.

  • For loop syntax
  • Iterating through strings
  • Iterating through lists
  • Iterating through tuples
  • Iterating through dictionaries
  • Continue statement
  • Break statement
  • Else statement

For loop syntax

Implementing a for loop in python is really easy. The syntax is as follows

for item in collection:
	print(item)

HERE,

  • for item in collection uses the for keyword to define a for loop that loops through a collected called collection picking one item at a time and assigning it to the variable called item. The full colon : at the end of the loop definition is mandatory.
  • print(item) the indented code forms the block of the for loop. To end the loop definition, you just have to remove the indentation.

Iterating through strings

Python actually treats strings like they are lists and each letter represents an item in the list. We can use a for loop to iterate through a string.

Let's look at a practical example.

word = 'Serengeti'

for letter in word:
    print(letter)

HERE,

  • word = 'Serengeti' defines a variable word and assigns the string value Serengeti to it.
  • for letter in word: defines a for loop that picks up the characters defined in the string.

The above code produces the following results

S
e
r
e
n
g
e
t
i

Let's now look at a slightly more advanced example that accepts a string then counts the number of vowels in it.

count = 0

for letter in word:
    vowels = 'aieou'

    if letter in vowels:
        count += 1


print(f'The word {word} has {count} vowels')

HERE,

  • count = 0 defines a variable count and initializes it to the value 0
  • for letter in word: defines a for loop that iterates through each letter in our word.
  • if letter in vowels: uses an if statement to check in the letter is in the vowels list and if true then the count variable in incremented by 1
  • print(f'The word {word} has {count} vowels') prints a formatted string in the console that contains the word and number of vowels that occur in it.

Lesson challenge

Rewrite the above code to count only unique vowels that occur in any given string. Feel free to share your solution in the comments section :)

Iterating through lists

Let's now look at how we can use a for loop to iterate through the elements in a list.

numbers = [1,2,3,4,5,6,7,8,9,10]

for number in numbers:
    print(number)

HERE,

  • numbers = [1,2,3,4,5,6,7,8,9,10] defines a list of numbers from 1 to 10.
  • for number in numbers: defines a for loop that iterates through each element in our list and prints out the value in the console.

The above code produces the following results

1
2
3
4
5
6
7
8
9
10

Let's now advance our above example and make it print out odd numbers only like so.

numbers = [1,2,3,4,5,6,7,8,9,10]


for number in numbers:
    if number % 2 != 0:
        print(number)

HERE,

  • if number % 2 != 0: we are using an if statement to check if the modulus of number is not equal to 0. If that is true then we print out the number.

Iterating through tuples

Let's now look at how we can go through the items of a tuple using the for loop

days = ('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday')

for day in days:
    print(day)

HERE,

  • days = (...) defines a tuple variables days that contains all days of the week.
  • for day in days: defines a for loop that iterates through all the days of the week and prints out the days in the console line by line.

The above code produces the following results

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Lesson challenge

Modify the above example and only print out weekends excluding working days.

Iterating through dictionaries

In this section, we will look at how we can work with a for loop to read a dictionary variable.

person = {
    'name':'Rodrick',
    'age':35,
    'gender':'Male'
}  

for key in person:
    print(f'The value of {key} is {person[key]}')

HERE,

  • person = {...} defines a dictionary with keys name,age,gender and assigns values to them.
  • for key in person: defines a for loop that loops through the keys of the dictionary.
  • print(f'The value of {key} is {person[key]}') uses a formatted string to print out a message that contains the key name and its corresponding value.

The above code produces the following results

The value of name is Rodrick
The value of age is 35
The value of gender is Male

Continue statement

The continue statement is used to stop the executing of the code block and moving on to the next item in the list.

Let's look at a practical example.

for n in list(range(10)):
    if n % 2 == 0:
        continue
    print(n)

HERE,

  • for n in list(range(10)): uses the for loop to loop through a list that we create using the range function and assigns the iteration element to the variable n
  • if n % 2 == 0: uses the modulus to check if the value of n is an even number. If the answer is yes then we call the continue statement to stop the execution and move on to the next on. If the condition is false then we proceed with execution and print out the odd number in the console.

The above code produces the following results.

1
3
5
7
9

Break statement

The break statement aborts the loop prematurely when the defined condition evaluates to true.

Consider the following code.

for n in list(range(10)):
    if n > 5:
        break
    print(n)

HERE,

  • for n in list(range(10)): we define a for loop that generates a list of numbers from 0 to 9
  • if n > 5: checks if the value of the variable n is greater than 5. If it is greater than 5 then we use the break statement to abort the loop.

The above code produces the following results

1
2
3
4
5

Note: numbers greater than 5 have not been printed.

Else statement

The else statement is optional and can be used to execute code immediately after the for loop finishes its execution.

for n in list(range(5)):
    print(n)
else:
    print('for loop looping has finished looping')

HERE,

  • else: defines the block of code that is executed immediately after the loop finishes. But if we break the for loop using the break statement then the else block will not be executed.

Lesson challenge

What will be printed in the for console when you execute the code below? Don't use the computer to solve it. Execute the code in your mind then share the answer in the comments section.

for n in list(range(5)):
    print(n)
    break
else:
    print('done looping...')

Summary

For loops are used to iterate through collections such as lists, tuples, dictionaries etc. The execution of the loop stops when all the items in a collected have been looped through. You can use the break statement to end the for loop prematurely. The continue statement is used to jump to the next item in the collection prematurely.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...