Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Explore the for Loop in Python | Loops in Python
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance with Python
2. Variables and Types in Python
3. Conditional Statements in Python
4. Other Data Types in Python
5. Loops in Python
6. Functions in Python

book
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:

123456
# Initial string word = 'Codefinity' # Initialize a for loop for i in word: print(i, end = ' ')
copy

Note

The variable i acts as an iterator, taking on the value of each character in the string word during each iteration of the for 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.

123456
# Initial list values = [1, [2, 3], 4, "code"] # Initialize a for loop for el in values: print(el, end = ' ')
copy

Note

The for loop doesn't require a predefined counter variable. Any variable name can be used, though programmers often choose common names like i or j. In the second example, el was used as a shorthand for 'element'.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt