Iterating through data structures is a fundamental concept in Python programming. The ability to loop over elements in a data structure allows you to perform operations and manipulate data efficiently. In this comprehensive guide, we will explore practical techniques for iterating through Python’s core data structures - lists, tuples, dictionaries, sets and custom objects.
Table of Contents
Open Table of Contents
Lists
Lists are Python’s most versatile ordered collection object. Let’s look at different ways to iterate through lists:
Basic For Loop
The basic way is using a for
loop combined with the range()
and len()
functions to iterate through the list index by index:
nums = [1, 2, 3, 4, 5]
for i in range(len(nums)):
print(nums[i])
# Outputs:
# 1
# 2
# 3
# 4
# 5
Enumerate
We can use the enumerate()
function to iterate through the list keeping track of both the index and value:
nums = [1, 2, 3, 4, 5]
for i, num in enumerate(nums):
print(i, num)
# Outputs:
# 0 1
# 1 2
# 2 3
# 3 4
# 4 5
Real Python: enumerate() Function
Zip
To loop over two or more lists simultaneously, zip()
can be used:
names = ['John', 'Jane', 'Joe']
ages = [25, 20, 18]
for name, age in zip(names, ages):
print(name, age)
# Outputs:
# John 25
# Jane 20
# Joe 18
List Comprehension
List comprehension provides a concise way to create new iterables by iterating through a list:
nums = [1, 2, 3, 4, 5]
squared_nums = [x**2 for x in nums]
print(squared_nums)
# Outputs:
# [1, 4, 9, 16, 25]
Real Python: List Comprehensions
While Loop
A while
loop can be used to iterate through a list until a condition is met:
names = ['John', 'Jane', 'Joe']
i = 0
while i < len(names):
print(names[i])
i += 1
# Outputs:
# John
# Jane
# Joe
Tuples
Tuples are immutable ordered sequences that work similarly to lists. Here are ways to iterate over tuples:
For Loop
Standard for
loop iteration:
colors = ('red', 'green', 'blue')
for color in colors:
print(color)
# Outputs:
# red
# green
# blue
Enumerate
enumerate()
can also be used:
digits = (0, 1, 2, 3, 4)
for i, digit in enumerate(digits):
print(i, digit)
# Outputs:
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
Zip
Zipping tuples works the same as lists:
names = ('John', 'Jane', 'Joe')
ages = (25, 20, 18)
for name, age in zip(names, ages):
print(name, age)
# Outputs:
# John 25
# Jane 20
# Joe 18
Tuple Unpacking
Iterating through tuples can be simplified by unpacking elements directly in the for
loop:
measurements = [(100, 20), (30, 15), (25, 10)]
for length, width in measurements:
print(length, width)
# Outputs:
# 100 20
# 30 15
# 25 10
Dictionaries
Dictionaries are unordered mappings of unique keys to values. Here are ways to iterate over dictionaries:
Iterating Keys
Use .keys()
to iterate over just the dictionary keys:
student_scores = {'Jane': 95, 'Bob': 87, 'Alex': 74}
for student in student_scores.keys():
print(student)
# Outputs:
# Jane
# Bob
# Alex
Iterating Values
Use .values()
to iterate over just dictionary values:
fruit_colors = {'apple': 'red', 'banana': 'yellow', 'grape': 'purple'}
for color in fruit_colors.values():
print(color)
# Outputs:
# red
# yellow
# purple
Iterating Keys and Values
Use .items()
to iterate through keys and values together:
product_info = {'apple': 1.99, 'orange': 2.35, 'peach': 4.50}
for product, price in product_info.items():
print(product, price)
# Outputs:
# apple 1.99
# orange 2.35
# peach 4.5
Dictionary Comprehension
Dictionary comprehension provides concise iteration to transform or filter dictionaries:
ages = {'Sue': 25, 'Bob': 30, 'Ann': 27}
over_30 = {name:age for name, age in ages.items() if age > 30}
print(over_30)
# Outputs:
# {'Bob': 30}
Python Docs: Dict Comprehensions
Sets
Sets are unordered collections of unique elements. Here are ways to iterate through sets:
For Loop
Basic for
loop:
vowels = {'a', 'e', 'i', 'o', 'u'}
for vowel in vowels:
print(vowel)
# Outputs:
# u
# a
# o
# i
# e
Sets have no indices, so elements are printed in an arbitrary order.
Set Comprehension
We can use set comprehension to iterate through a set and perform some operation:
nums = {1, 3, 5, 7, 9}
squared = {x**2 for x in nums}
print(squared)
# Outputs:
# {1, 9, 25, 49, 81}
Custom Objects
To iterate through custom classes, define an __iter__()
method that yields item values:
class AnimalNames:
def __init__(self):
self.names = ['Lion', 'Zebra', 'Cat']
def __iter__(self):
for name in self.names:
yield name
animal_names = AnimalNames()
for name in animal_names:
print(name)
# Outputs:
# Lion
# Zebra
# Cat
Conclusion
Iterating through data structures provides a powerful way to manipulate and transform data in Python. The key takeaways include:
- Use
for
loops, list/dict comprehensions andwhile
loops to iterate through sequence data types like lists, tuples, strings. - Utilize built-in functions like
enumerate()
,zip()
,keys()
,values()
anditems()
for more flexible iterations. - Comprehensions provide concise syntax for iterations.
- Sets require basic
for
loops but set comprehensions can also be useful. - For custom classes, define
__iter__()
and yield values.
With these techniques, you can write concise yet flexible Python code to effectively process data in your programs.