Python for Loop (with Examples)

The Python 'for' loop is used to repeat a code N number of times, where N is the number of items in the sequence or iterable. In Python, we can use for loop to iterate over the elements of the following data types:

  • List
  • Tuple
  • Dictionary
  • Set
  • String
  • Range

The syntax to use a for loop is:

for val in sequence:
	statement(s)

Here, the variable val represents a value from the sequence, for the current iteration. After each iteration. the value points to the next available value in the sequence. Once all the values have been iterated, the for loop terminates.

1. Python for Loop with List

Python program to iterate over a list of items using for loop. This program prints all the names stored in the list.

names = ["alex", "brian", "charles"]
for x in names:
  print('Current name is :', x)

The program output:

Current name is : alex
Current name is : brian
Current name is : charles

2. Python for Loop with Tuple

Python program to iterate over a tuple of items using for loop. This program prints all the names stored in the list.

mytuple = ("item1", "item1", "item3")

for e in mytuple:
    print("Current item is", e)

The program output:

Current item is item1
Current item is item1
Current item is item3

3. Python for Loop with Dictionary

A dictionary is a collection data type and we can iterate over its key-value pairs as follows:

colors_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

for key in colors_dict.keys():
    print(key)

for item in colors_dict.items():
    print(item)

The program output:

color
fruit
pet
('color', 'blue')
('fruit', 'apple')
('pet', 'dog')

4. Python for Loop with Set

We can also iterate the elements of a Python set using the Python for loop instruction. Consider the following example where we are iterating over a set of 3 elements.

myset = set(["item1", "item2", "item3"])

for e in myset:
    print("Current item is", e)

The program output:

Current item is item3
Current item is item2
Current item is item1

5. Python for Loop with String

In Python, strings are iterable. They are a sequence of characters, so we can iterate over the characters as follows:

name = "alex"
for x in name:
  print("Current char is", x)

The program output:

Current char is a
Current char is l
Current char is e
Current char is x

6. Python for Loop with range()

In Python, the for loop can be used with range() function as well. The range() generates a sequence of values starting with 0 by default. For example, range(10) will generate numbers from 0 to 9 (10 numbers).

for i in range(5):
	print(i)

The program output:

0
1
2
3
4

7. The break and continue Statements

The break statement is used to stop the iteration and exit the for loop, when a certain condition is met:

names = ["alex", "brian", "charles"]

print("Loop started")

for x in names:
  print(x)
  if x == "brian":
  	break;

print("Loop ended")

The program output:

Loop started
alex
brian
Loop ended

The continue statement is used to stop the current iteration and jump to the next iteration in the loop. It does not terminate the for loop.

names = ["alex", "brian", "charles"]

print("Loop started")

for x in names:
  if x == "brian":
  	continue;
  print(x) 

print("Loop ended")

The program output:

Loop started
alex
charles
Loop ended

8. The else Statement

The for loop can have an optional else block as well. It is called for...else statement.

names = ["alex", "brian", "charles"]
 
for x in names:
  print(x) 
else:
  print("No name is left in the list") 

The program output:

alex
brian
charles
No name is left in the list

Drop me your questions related to the listed Python for loop examples.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode