Course Content
Introduction to Python
Introduction to Python
for Loop
When you need to loop through a specific set of values, the for
loop is your go-to in Python. Unlike some other languages, you don't need a predefined counter variable for this loop. Instead, you use an iterator variable, which you don't have to define ahead of time.
Python for
loops can work with sequence types, including lists, tuples, strings, and dictionaries. For instance, if you loop through a string:
# Initial string word = 'Codefinity' # Initialize a for loop for i in word: print(i, end = ' ')
Note
In this code,
i
is a variable that takes on the value of each character in the stringword
during each iteration of thefor
loop. As the loop progresses,i
sequentially represents each character in 'Codefinity', and each character is printed out.
As shown, the loop runs through each character (or element) of the string. Similarly, when looping through a list, it covers every item in that list.
# Initial list values = [1, [2, 3], 4, "code"] # Initialize a for loop for el in values: print(el, end = ' ')
Note
The
for
loop doesn't need you to set up a counter variable in advance. You're free to pick any variable name that suits you. Many programmers gravitate towards names likei
orj
. In our second example, we opted forel
, short for 'element'.
Thanks for your feedback!