Instagram
youtube
Facebook
Twitter

for loop

for Statement

  • for statement in python is used to iterate or repeat a set of statements or lists or strings or any sequence.
  • In python, the for loop works better than the c language as it does not iterate over any numeric conditions.
  • You can apply for loop in python over the list, string, tuple, dictionary, etc.

 

Example - For loop over a list of string

name_list = ["Mradul", "Manal", "Hardik", "Sachin", "Gautam"]

for i in name_list:
    print(i)


Output - 

Mradul
Manal
Hardik
Sachin
Gautam

 

  • Here in this example, we have taken a list of strings named name_list.
  • Then for loop statement is written - for i in name_list:
  • This means iterating the list and placing the value of each element in the list inside i one by one.
  • print(i) outputs each data item inside the list one by one.

 

For example - for looping over a dictionary

#Created a dictionary 
users = {'Mradul': 'active', 'Manal': 'inactive', 'Hardik': 'active'}

#Added for loop statement
for user, status in users.items(): #Here user is key and status is value
    if status == 'inactive':
        del users[user]

 

The range() Function

  • If you want to iterate the loop over a sequence of numbers between a range then the range function is used inside for loop.
for i in range(5):
    print(i)

Output- 
0
1
2
3
4

 

  • Here in the above example, the loop runs five times as the range function has an argument 5.
  • If you want to run the range function in a custom range then need to write range(2, 5). This will iterate the loop three times. The start point would be 2 and the end point would be 4.