DEV Community

Justin Bermudez
Justin Bermudez

Posted on

2 1

Different Types of Loops in Python

In this post I will show several loops in Python that you can utilize for your problems in python.

For Loop

For loop allows you to go over a dictionary, set, string, list, or tuple.

# loop over array example
array = [1, 2, 3, 4]
for x in array:
    print(x)

=> 1
=> 2
=> 3
=> 4

Loop Over String

string = "word"
for x in string:
    print(x)

=> w
=> o
=> r
=> d

Keep in mind, the printed out characters are of type string!

Loop over Set

Sets are unordered collections that have no duplicate elements

word = set("uniq")
for x in word:
    print(x)

=> u
=> n
=> i
=> q

Looping with range

Using range takes in a number to loop. You can use the length of an array for instance to iterate through the whole array.
Range will go by index so it will begin at 1 and end at the length - 1

array = [1, 2, 3, 4]
for i in range(len(array)):
    print("index:"i, ", value:", array[i])

=> index: 0 , value: 1
=> index: 1 , value: 2
=> index: 2 , value: 3
=> index: 3 , value: 4

While Loops

While loops continue to loop until the condition is met. Be careful using while loops because you can easily have an infinite loop.

counter = 0
while counter < 5:
    print(counter)
    counter += 1

=> 0
=> 1
=> 2
=> 3
=> 4

Not incrementing the counter here would result in an infinite loop and may timeout the program.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay