Skip to content

Python iteration

  • by

The Repeated execution of a set of statements is called iteration in Python. Iteration means taking an object like a list or a tuple (an object that has more than one value) and going through those values.

Python iteration

Simple example code Using Iterations in Python Effectively.

Use of for-in (or for each)

The iterator fetches each component and prints data while looping.

cars = ["BMW", "Audi", "McLaren"]
for x in cars:
    print(x)

Output:

Python iteration

Enumerate:

The Enumerate is a built-in Python function that takes input as an iterator, list, etc, and returns a tuple containing an index and data at that index in the iterator sequence.

cars = ["BMW", "Audi", "McLaren"]
for x in enumerate(cars):
    print (x[0], x[1])

Output:

0 BMW
1 Audi
2 McLaren

for loop: It iterates over a sequence (such as a list, tuple, string, or range) and executes the block of code for each item in the sequence.

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

while loop: It repeatedly executes a block of code as long as a specified condition is true.

# Using a while loop to print numbers from 1 to 5
num = 1
while num <= 5:
    print(num)
    num += 1

Iterating over dictionaries: You can iterate over dictionaries using the items() method to access both keys and values or using the keys() or values() methods to iterate over keys or values, respectively.

# Iterating over dictionary items
ages = {"John": 30, "Alice": 25, "Bob": 35}
for name, age in ages.items():
    print(f"{name} is {age} years old")

Using built-in functions: Python provides some built-in functions for iteration, such as map(), filter(), and reduce() (in Python 2, reduce() is in the functools module).

# Using map() to apply a function to every element in a list
nums = [1, 2, 3, 4, 5]
squared = map(lambda x: x**2, nums)
print(list(squared))  # Output: [1, 4, 9, 16, 25]

These are some of the primary ways to perform iteration in Python, each suited for different situations and data types.

Do comment if you have any doubts or suggestions on this Python basic topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading