Python for Loop

Generally, a 'for' loop is used to repeat a code N number of times, where N is the number of items in the sequence or collection. In Python, we can use for loop to iterate over a list, a tuple, a dictionary, a set, or a string.

chars = ["a", "b", "c"]

for c in chars:
    print(c)

1. Syntax

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.

2. Python for Loop Examples

2.1. Looping through a 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(x)

2.2. Looping through a 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(x)

2.3. Looping through a 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)

3. 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 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")

4. 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") 

5. Looping within 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)

Drop me your questions related to python for loop and its examples.

Happy Learning !!

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