python

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?