For loop is one of the most important fundamental concepts of any programming language. As a Python developer, have you ever faced tasks that involved repeating the same action multiple times. For example, if your mom asked you to fill water bottles and place them in the fridge, you would repeat the same task for each bottle.
Similarly, in programming, you may encounter scenarios where you frequently need to repeat actions, for example, printing natural numbers from 1 to 100 or even 20,000. Writing each print() statement manually would be a nearly impossible and inefficient approach. This is where loops come into action, saving time and effort by automating repetitive tasks.
In this blog post, I will introduce you to the concept of loops in Python, focusing specifically on for loops
, and how they enhance Python’s power and efficiency.
Table of Contents
What is Loop?
A loop in programming allows you to execute a block of code multiple times without writing it multiple times. For example, if I asked you to print the numbers from 1 to 5. Without a loop, we would write:
print(1)
print(2)
print(3)
print(4)
print(5)
# Output
# 1
# 2
# 3
# 4
# 5
PythonThis works for now, but what if you had to print all numbers from 1 to 200,000? Writing each line manually would be impractical, or you may write it, but it takes a lot of time. Instead, a loop can automate the process for you in minutes. We will learn about this below.
Types of Loops in Python
In python, there are mainly 2 types of loop.
- For Loop. This use when the number of iterations is known.
- While Loop. This use when the number of iterations is unknown and depends on a condition.
While both loops are used for the same purpose of repeating code, But they do so in different ways. In this blog we will focus on the for
loop, which is particularly useful when you know the number of iterations in advance.
For loop
The for loop is used using for
keyword to iterate over a sequence such as a list, tuple, dictionary, range(), or string.
Syntax:
for <item> in <iterable>:
# code block
Python- The loop starts with the keyword
for
, followed by a variable name<item>
. - The
in
keyword is used to specify the sequence (list, string, range) that the loop will iterate over. - The Code Block is the part of the code that is indented and will run for each in the
<iterable>
. The indentation is important in Python because it shows what is included in the loop.
How the for loop works?
Here is a step-by-step breakdown of what happens when the for loop is executed with an example:
1. Starting the Loop
When you write a for loop, you specify a collection or sequence. This could be a list of fruits, a string of characters, or even a range of numbers.
For example,
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# output
# apple
# banana
# cherry
Python2. Taking the First Element
The for loop begins by looking at the first item in the sequence. In our example, the first item is apple. Python takes this first item and assigns it to a variable that you specified in the loop. In our example we named our variable fruit
. So now, fruit
holds the value "apple"
.
3. Executing the Code Block
After assigning the first item to the variable, Python executes the block of code that is indented under the for loop. This is the part of the code that you want to repeat for each item.
4. Moving to the Next Element
Once the code block has been executed for the first item, the for loop moves on to the next item in the sequence. In our case, it now looks at the second item, which is banana.
Python assigns this new value to the same variable fruit
. So now, fruit holds the value "banana"
.
5. Continuing to All Elements
The loop going through each item in the sequence one by one. For our list of fruits, and once the loop has gone through all the items in the sequence (in this case, all three fruits), it stops. There are no more items to process, so the loop ends.
Example 2:
word = "hello"
for letter in word:
print(letter)
#output
# h
# e
# l
# l
# o
PythonThis loop iterates over a string and prints each letter one by one.
Example 3:
student_scores = {"Alice": 85, "Bob": 90, "Charlie": 78}
for student in student_scores:
print(student, "scored", student_scores[student])
#output
# Alice scored 85
# Bob scored 90
# Charlie scored 78
PythonThis loop iterates over the keys (student names) in the dictionary and prints each student’s name along with their score.
Example 4:
unique_numbers = {1, 2, 3, 4, 5}
for number in unique_numbers:
print(number)
#output
# 1
# 2
# 3
# 4
# 5
PythonThis loop iterates over each unique number in the set and prints each number. The order of output may vary since sets are unordered.
The range() Function
The range()
function is a built-in function in Python that generates a sequence of numbers. It is commonly used in for
loops to specify the number of iterations. The numbers generated by this function can be used for various purposes, such as iterating over a sequence or creating lists of numbers.
Syntax:
range(start, stop, step)
Pythonstart
(optional): This is the first number in the sequence. If you don’t give a value, it will start at0
by default.stop
: This is the last number in the sequence (not included). The sequence will create numbers up to, but not including, this number.step
(optional): This is the amount of difference between each number in the sequence. If you don’t specify it, the default is1
. It can be a positive or negative number.
For example:
range(10)
# Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(1, 11)
# Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
range(2, 20, 2)
# Output: 2, 4, 6, 8, 10, 12, 14, 16, 18
range(5, 0, -1)
# Output: 5, 4, 3, 2, 1
range(10, 0, -2)
# Output: 10, 8, 6, 4, 2
range(0)
# Output: (empty sequence)
PythonWhy do we need loops?
Loop are essential parts of programming because:
- It is used to automate the repetitive tasks means there is no need to write same code again and again.
- Make programs more efficient and readable.
- It allow data processing like iterating through a list of items.
- Reduce redundancy in code.
- saves time and efforts
Conclusion
In this blog, we explored the for loop in Python and its versatility in iterating over various data structures, including lists, strings, dictionaries, ranges, and sets. The for loop is a powerful tool in Python. Understanding its syntax is the first step to using it effectively in your programs. Next you will be learning about while loop, nested loops, and jump statements.