For Loop In Python Examples

for loop in python examples

Our Python articles also frequently mentioned the for loop when solving problems. Today we will introduce for loop in more detail to you through for loop in Python examples. Continue reading the article to know more.

The for loop in Python examples for beginners

Below, we’ll show you the for loop examples in Python that even a beginner can understand.

Loop through a string

The for loop is used to iterate through iterable objects such as lists, tuples, and even strings.

We can use the for loop with a string like this:

string = ""

for char in string:
    # Print in the same line
    print(char, end = " ")


l e a r n s h a r e i t . c o m 

You can do the same with a list or tuple like the one below.

Loop through a list of numbers

The list data type is the most common type for storing multiple values. We can use for loop to iterate through a list as follows:

score = [1, 3, 4, 2, 3, 9, 11]
total = 0

for num in score:
    # Get the sum of the numbers in the list
    total += num

print("Total: ", total)


Total: 33

Break and continue keywords in the Python loop

Like their name, the break keyword stops the loop before iterating over all the elements. The continue keyword skips the current loop to jump to the next loop.

Suppose we want to get the sum of even numbers in a list. If their sum exceeds 20, we will stop the loop. Here is how:

numbers = [1, 3, 4, 2, 3, 8, 11, 8]
total = 0

for num in numbers:
    # If num is odd -> jump to the next loop
    if num % 2 != 0:

    # Get the sum
    total += num

    # If total > 20 -> back to the previous value and stop the loop
    if total > 20:
        total -= num

print("Total: ", total)


Total: 14

Combine for loop with range() and len()

for(i = 0; i < list.length; i++) Do you find it familiar?

In Python, we have the same way, but the syntax is much easier to see and read using range() in combination with len(). Like this:

languages = ["Python", "JavaScript", "PHP", "Java", "C#"]

#  Combine for loop with range() and len() function
for i in range(len(languages)):
    print(i, languages[i])


0 Python
1 JavaScript
3 Java
4 C#


We can use the for loop in combination with Comprehension in Python to quickly create data structures like list, set, and dict. Here’s how to use a for loop with List Comprehension to quickly create a list object.

# Use for loop and List Comprehensions to create a list object
listObj = [i for i in range(1, 11)]


[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Python for loop tutorials

You can learn more about Loop in Python in the articles below:


That’s all for the for loop examples. We hope the above examples have given you a better understanding of for loop in Python examples. Regularly visit LearnShareIT to learn new knowledge about Python.

Leave a Reply

Your email address will not be published. Required fields are marked *