Search code snippets, questions, articles...

For loop python

For loop in python is used to iterate over python collections like Lists, dictionaries, etc
#LOOP THROUGH LIST
names = ["John", "Sonia", "Rakesh"]
for item in names:
    print(item)

#LOOP THROUGH DICTIONARY
my_dict = {
    "name": "John",
    "title": "Programmer",
    "lang": "Python"
}

for key in my_dict:
    print(key, "is: ", my_dict[key])

# Loop through list of dictionaries
subjects = [
    { "name": "English", "score": 90 },
    { "name": "Math", "score": 100 },
    { "name": "Physics", "score": 90 }
]

for subject in subjects:
    print("Subject Name is: ", subject['name'], " Score is: ", subject['score'])
Output
John
Sonia
Rakesh

name is: John
title is: Programmer
lang is: Python

Subject Name is: English Score is: 90
Subject Name is: Math Score is: 100
Subject Name is: Physics Score is: 90

For loop in python is very simple to understand. In the above code snippets, we are printing names that exist in the list. We are using for loop to print them. The 'item' keyword will get each name that exists in the names list one by one.

Was this helpful?
1 Comments

You can also use break and continue keywords in python to break the loop or to skip an iteration

Break a loop

The 'break' keyword is used to break the iterations of 'for loop' in python. You can understand it with the below code:

names = ["John", "Sonia", "Rakesh"]
for item in names:
    print(item)
    if item == "Sonia":
        break

So if item equals to 'Sonia', the loop iterations will not execute further. So the above code will output only 'John' and 'Sonia'.

Skip an iteration using continue statement

You can skip an iteration using 'continue' keyword. The below code will skip the iteration if the name is Sonia.

names = ["John", "Sonia", "Rakesh"]
for item in names:
    if item == "Sonia":
        continue
    print(item)
    

The above code will print 'John' and 'Rakesh' as output as we have applied a condition on second item.

Programming Feeds
Learn something new everyday on Devsheet