Posts Python for loop
Post
Cancel

Python for loop

For Loop

| For loop is generally used to avoid repeated code. and to perform same action in a loop

The For loop can be used with any iterable items

  • string
  • list
  • tupple
  • Dictionary etc.
    Syntax
    1
    2
    
    for item in object:
      statements to do stuff
    

Example 1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
>>> list1 = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> for num in list1:
...     print(num )
...
1
2
3
4
5
6
7
8
9
10
11
12

| In above you could see num is a variable and on each loop it got replaced with the element.

Example 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> a = (('a', 'b', 'c'), ('d', 'e', 'f'), ('i', 'j', 'k'))
>>> for q,v,d in a:
...     print(q)
...     print(v)
...     print(d)
...
a
b
c
d
e
f
i
j
k
>>> for q,v,d in a:
...     print(q)
...
a
d
i

In Example 2 you could see we are assigning 3 variables q v and d on the fly and each variable will be mapped to respective positioned values.

For practice try the same with list as input


Thanks for reading till end.

Followus on insta @techpechu

Join Our Discord

We do run a youtube channel in Indian regional language Tamil called TechPechu. Do subscribe us for moral support. Happy Learning.

Follow us on instagram @techpechu