Course Content
Introduction to Python
Introduction to Python
Explore the for Loop in Python
When looping through a specific set of values, the for
loop is the ideal choice in Python. Unlike some other languages, it does not require a predefined counter variable. Instead, it uses an iterator variable, which does not need to be declared beforehand.
Python for
loops work with various sequence types, including lists, tuples, strings, and dictionaries. For example, when iterating over a string:
# Initial string word = 'Codefinity' # Initialize a for loop for i in word: print(i, end = ' ')
Note
The variable
i
acts as an iterator, taking on the value of each character in the stringword
during each iteration of thefor
loop. As the loop runs,i
sequentially represents each character in"Codefinity"
, printing them one by one.
As demonstrated, the loop iterates through each character (or element) in the string. Likewise, when looping through a list, it processes each item in the list one by one.
# 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 require a predefined counter variable. Any variable name can be used, though programmers often choose common names likei
orj
. In the second example,el
was used as a shorthand for'element'
.
Thanks for your feedback!