Python for Loops

Python for Loops

In any programming language, for loops are commonly used for iteration purposes. In Python for loop is used if you want a sequence to be iterated. The sequence could be anything like a list, a dictionary, a string, a set, etc. The usage of for loop in python is similar to most of the other programming languages, using the for loops, it’s just that syntactically the use of for keyword in python is different in Python.

Imagine anything that contains a set of similar items. Any such set could be iterated using Python For Loop. Let’s understand the usage of for loop with examples on different sequences including the list, dictionary, string, and set.

Python For Loop On List

Let’s say there’s a list that contains the names of four people. Now, I can make use of for loop here to print the names of each student one by one. The example code and screenshot of the code output are given below.

names = ["Ramesh", "Suresh", "Johnny"]
for name in names:
    print(name)

Therefore, the generic syntax to use for loop to iterate over a list in python is as defined below.

for {current-iteration-variable} in {list-variable}:
  print({current-iteration-variable})

The usage of for loop, in this case, does not require any initialization of a variable and therefore it is similar to foreach used in some other programming languages.

Python For Loop On Strings

As strings are also a set of individual characters, therefore strings can also be iterated in python. An example to iterate strings in python is given below.

for character in "somestring":
    print(character)

The Generic Syntax to use for the keyword for iteration of the string will be as defined below.

for {current-iteration-variable} in {string-variable}:
  print({current-iteration-variable})

Break Statement in Python For Loop

You can choose to stop the iteration anytime in between according to some conditions using the break statement in python.

The syntax and example for the break statement are given below in which the loop is iterating till it founds a particular name in the list.

names = ["Ramesh", "Suresh", "Sheila", "Kamlesh"]
for name in names:
    print(name)
    if name == "Sheila":
        break

In the above code, the break statement is written after the print statement, therefore, it is printing the name where it was asked to break as well. But if you’ll put the if statement before the print statement, the current name in the if statement will also not be printed.

Make sure that the iteration will immediately stop as soon as it encounters the break statement and if any code is written after the break statement in the current iteration block code, it will not be executed.

The Continue Statement

The continue statement can be used whenever and wherever you don’t want more code from the current iteration block to be executed and simply want to move to the next iteration of the sequence.

Let’s take the same example. Here, the thing is if I just don’t want to print one of the names, I’ll use the if statement to check the name and simply put the continue statement before the print statement to move to the next iteration and avoid printing the current name.

names = ["Ramesh", "Suresh", "Sheila", "Kamlesh"]
for name in names:
    if name == "Sheila":
        continue
    print(name)

The Range Function (The Traditional For Loop)

A lot of people knowing other programming languages, find themselves a bit amazed to see the working of for loop as it works in most of the other languages. In all of the above examples, we haven’t set any initialization variables. So, what we should do to iterate the sequence over a range, like from 1 to 100.

It can be done using the range() function in python. The range() function can take up to 3 parameters. By default, the first parameter is 0 and if you provide it only one parameter, it takes it as the second parameter.

For example, range(5) will output will include the values 0,1,2,3,4 and range(2,5) will give include the values 2,3 and 4.

The usage of range with for loop in python will be as specified below.

for i in range(7):
    print(i)
for i in range(2, 7):
    print(i)

Sequence Increment By A Custom Number

The range function basically increments the value by 1 if the third parameter is not specified. The third parameter is the increment number. For example, the following for loop prints the number after incrementing 5.

for i in range(2, 50, 5):
    print(i)

For Loop & Else Statement

Python for loops has an interesting use of else statements. If you want some piece of code to be executed right after the loop completed all of its iterations, then you can put the code in the else block.

for i in range(3):
    print(i)
else:
    print("Completed For Loop")

Python Nested For Loops

Nested means something inside itself. Therefore a for loop inside another for loop is the case of nesting in for loops. The inner loops are executed once completely for each iteration run by its parent loop.

abc = ["A","B","C"]
bcd = ["X","Y","X"]

for x in abc:
    for y in bcd:
        print(x + y)

Use your creativity to make use of the for loops in an even better way.

Leave a Reply

Your email address will not be published. Required fields are marked *