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

Course Content

Introduction to Python

Introduction to Python

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

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

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

Note

In this code, i is a variable that takes on the value of each character in the string word during each iteration of the for 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.

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 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 like i or j. In our second example, we opted for el, short for 'element'.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
some-alt