Using Iterations in Python Effectively
Last Updated :
06 Mar, 2023
Prerequisite: Iterators in Python Following are different ways to use iterators.
C-style approach: This approach requires prior knowledge of a total number of iterations.
Python
# A C-style way of accessing list elements
cars = ["Aston", "Audi", "McLaren"]
i = 0
while (i < len(cars)):
print cars[i]
i += 1
Python3
# A C-style way of accessing list elements
cars = ["Aston", "Audi", "McLaren"]
i = 0
while (i < len(cars)):
print(cars[i])
i += 1
Important Points:
- This style of looping is rarely used by python programmers.
- This 4-step approach creates no compactness with a single-view looping construct.
- This is also prone to errors in large-scale programs or designs.
- There is no C-Style for loop in Python, i.e., a loop like for (int i=0; i<n; i++)
Use of for-in (or for each) style: This style is used in python containing iterator of lists, dictionary, n dimensional-arrays, etc. The iterator fetches each component and prints data while looping. The iterator is automatically incremented/decremented in this construct.
Python
# Accessing items using for-in loop
cars = ["Aston", "Audi", "McLaren"]
for x in cars:
print x
Python3
# Accessing items using for-in loop
cars = ["Aston", "Audi", "McLaren"]
for x in cars:
print(x)
Output:
Aston
Audi
McLaren
See this for more examples of different data types.
Indexing using Range function: We can also use indexing using range() in Python.
Python
# Accessing items using indexes and for-in
cars = ["Aston", "Audi", "McLaren"]
for i in range(len(cars)):
print cars[i]
Python3
# Accessing items using indexes and for-in
cars = ["Aston", "Audi", "McLaren"]
for i in range(len(cars)):
print(cars[i])
Output:
Aston
Audi
McLaren
Enumerate: Enumerate is a built-in python function that takes input as iterator, list etc and returns a tuple containing index and data at that index in the iterator sequence. For example, enumerate(cars), returns a iterator that will return (0, cars[0]), (1, cars[1]), (2, cars[2]), and so on.
Python
# Accessing items using enumerate()
cars = ["Aston", "Audi", "McLaren "]
for i, x in enumerate(cars):
print(x)
The below solution also works.
Python
# Accessing items and indexes enumerate()
cars = ["Aston" , "Audi", "McLaren "]
for x in enumerate(cars):
print (x[0], x[1])
Output :
(0, 'Aston')
(1, 'Audi')
(2, 'McLaren ')
We can also directly print returned value of enumerate() to see what it returns.
Python
# Printing return value of enumerate()
cars = ["Aston" , "Audi", "McLaren "]
print (enumerate(cars))
Output :
<enumerate object at 0x7fe4f914d3c0>
Enumerate takes parameter start which is default set to zero. We can change this parameter to any value we like. In the below code we have used start as 1.
Python
# demonstrating the use of start in enumerate
cars = ["Aston" , "Audi", "McLaren "]
for x in enumerate(cars, start=1):
print (x[0], x[1])
Output(1, 'Aston')
(2, 'Audi')
(3, 'McLaren ')
enumerate() helps to embed the solution for accessing each data item in the iterator and fetching index of each data item.
Looping extensions:
i) Two iterators for a single looping construct: In this case, a list and dictionary are to be used for each iteration in a single looping block using enumerate function. Let us see an example.
Python
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS kit", "Car repair-tool kit"]
# Single dictionary holds prices of cars and
# its accessories.
# First three items store prices of cars and
# next two items store prices of accessories.
prices = {1: "570000$", 2: "68000$", 3: "450000$",
4: "8900$", 5: "4500$"}
# Printing prices of cars
for index, c in enumerate(cars, start=1):
print "Car: %s Price: %s" % (c, prices[index])
# Printing prices of accessories
for index, a in enumerate(accessories, start=1):
print("Accessory: %s Price: %s"
% (a, prices[index+len(cars)]))
Python3
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS kit", "Car repair-tool kit"]
# Single dictionary holds prices of cars and
# its accessories.
# First three items store prices of cars and
# next two items store prices of accessories.
prices = {1: "570000$", 2: "68000$", 3: "450000$",
4: "8900$", 5: "4500$"}
# Printing prices of cars
for index, c in enumerate(cars, start=1):
print("Car: %s Price: %s" % (c, prices[index]))
# Printing prices of accessories
for index, a in enumerate(accessories, start=1):
print("Accessory: %s Price: %s"
% (a, prices[index+len(cars)]))
OutputCar: Aston Price: 570000$
Car: Audi Price: 68000$
Car: McLaren Price: 450000$
Accessory: GPS kit Price: 8900$
Accessory: Car repair-tool kit Price: 4500$
ii) zip function (Both iterators to be used in single looping construct): This function is helpful to combine similar type iterators(list-list or dict- dict etc,) data items at ith position. It uses the shortest length of these input iterators. Other items of larger length iterators are skipped. In case of empty iterators, it returns No output.
For example, the use of zip for two lists (iterators) helped to combine a single car and its required accessory.
Python
# Python program to demonstrate the working of zip
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS", "Car Repair Kit",
"Dolby sound kit"]
# Combining lists and printing
for c, a in zip(cars, accessories):
print "Car: %s, Accessory required: %s"\
% (c, a)
Python3
# Python program to demonstrate the working of zip
# Two separate lists
cars = ["Aston", "Audi", "McLaren"]
accessories = ["GPS", "Car Repair Kit",
"Dolby sound kit"]
# Combining lists and printing
for c, a in zip(cars, accessories):
print("Car: %s, Accessory required: %s" % (c, a))
OutputCar: Aston, Accessory required: GPS
Car: Audi, Accessory required: Car Repair Kit
Car: McLaren, Accessory required: Dolby sound kit
The reverse of these iterators from zip function is known as unzipping using “*” operator. Use of enumerate function and zip function helps to achieve an effective extension of iteration logic in python and solves many more sub-problems of a huge task or problem.
Python
# Python program to demonstrate unzip (reverse
# of zip)using * with zip function
# Unzip lists
l1,l2 = zip(*[('Aston', 'GPS'),
('Audi', 'Car Repair'),
('McLaren', 'Dolby sound kit')
])
# Printing unzipped lists
print(l1)
print(l2)
Output:
('Aston', 'Audi', 'McLaren')
('GPS', 'Car Repair', 'Dolby sound kit')
Similar Reads
Execute a String of Code in Python Sometimes, we encounter situations where a Python program needs to dynamically execute code stored as a string. We will explore different ways to execute these strings safely and efficiently.Using the exec function exec() function allows us to execute dynamically generated Python code stored in a st
2 min read
How to Use Pytest for Efficient Testing in Python Writing, organizing, and running tests is made easier with Pytest, a robust and adaptable testing framework for Python. Developers looking to guarantee code quality and dependability love it for its many capabilities and easy-to-use syntax. A critical component of software development is writing tes
5 min read
Python in Competitive Programming In 2017, when ACM allowed Python support for its prestigious competition, the ACM ICPC, a whole new community became interested in the sport of competitive programming. This meant more people coming back to the basics, learning algorithms that are the building blocks of complex packages they use to
3 min read
Introduction to Python GIS Geographic Information Systems (GIS) are powerful tools for managing, analyzing, and visualizing spatial data. Python, a versatile programming language, has emerged as a popular choice for GIS applications due to its extensive libraries and ease of use. This article provides an introduction to Pytho
4 min read
Access List Items in Python Accessing elements of a list is a common operation and can be done using different techniques. Below, we explore these methods in order of efficiency and their use cases. Indexing is the simplest and most direct way to access specific items in a list. Every item in a list has an index starting from
2 min read