DEV Community

Cover image for Python For Loops
Karthick (k)
Karthick (k)

Posted on

Python For Loops

Python for loops are used to iterate over sequences such as lists, tuples, strings and ranges.

  • Allows the same operation to be applied to every item in a sequence.
  • Avoids the need to manage loop indices manually.

a = ["Geeks", "for", "Geeks"]
for i in a:
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output:

Geeks
for
Geeks

Syntax

for variable in sequence:
    # code block
Enter fullscreen mode Exit fullscreen mode

Loop Through String

Here, a for loop is used to iterate through each character of the string and print them one by one.

s = "Geeks"
for i in s:
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output

G
e
e
k
s

range() Method

range() function is used with for loops to generate a sequence of numbers. It can take one, two or three arguments:

  • range(stop) generates numbers from 0 to stop-1.
  • range(start, stop) generates numbers from start to stop-1.
  • range(start, stop, step) generates numbers from start to stop-1, incrementing by step.
for i in range(0, 10, 2):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Output
0
2
4
6
8

Top comments (0)