Python for loop example

A for loops works as an iterator it pyhton. You can go through all the elements of the sequence or map.

Here’s the general syntax for a for loop in Python:

You can change variable name item here and I would suggest having good variable names so program can be easy to understand.

Let’s take some example and iterate over few data structures.


Iterate over list

# We'll learn how to automate this sort of list in the next lecture lst = [1,2,3,4,5,6,7,8,9,10] for num in lst: print(num)

Output:

1
2
3
4
5
6
7
8
9
10

Let’s double the even number in the list and print it.

lst = [1,2,3,4,5,6,7,8,9,10] for num in lst: if(num%2==0): print(num*2)

Output:

4
8
12
16
20

Let’s create a loop that iterates over list and calculates sum of list.

lst = [1,2,3,4,5,6,7,8,9,10] # Start sum at zero list_sum = 0 for num in lst: list_sum = list_sum + num print(list_sum)

output:

55

Iterate over String

We can access each character of String using for loop.
For example:

for char in 'Welcome to code2master': print(char)

Output:

W
e
l
c
o
m
e

t
o

c
o
d
e
2
m
a
s
t
e
r


Iterate over tuple

Let’s iterate over tuple.It is very much similar to list

t = (1,2,3,4,5) for item in t: print(item)

Output:

1
2
3
4
5

Iterate over map

countryDict = {'India':'Delhi','Nepal':'Kathmandu','Bhutan':'Thimpu'} for item in countryDict: print(item)

Output:

India
Nepal
Bhutan

Did you notice, we just able to print keys above.
Let’s now print keys and values.We can use items method of dictionary to print it.
items method returns a list of tuples which you can iterate.

countryDict = {'India':'Delhi','Nepal':'Kathmandu','Bhutan':'Thimpu'} for country,capital in countryDict.items(): print(country,capital)

Output:

India Delhi
Nepal Kathmandu
Bhutan Thimpu

That’s all about Python for loop.

Leave a Reply

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