Skip to content

Commit e1deb5b

Browse files
authored
Merge pull request #519 from realpython/python-lazy-evaluation
python-lazy-evaluation
2 parents 88d689a + aba40d2 commit e1deb5b

File tree

10 files changed

+211
-0
lines changed

10 files changed

+211
-0
lines changed

python-lazy-evaluation/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# What's Lazy Evaluation in Python?
2+
3+
A summary of the code used in the [What's Lazy Evaluation in Python?](https://realpython.com/python-lazy-evaluation/) tutorial on Real Python.
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Exploring the itertools module
3+
"""
4+
5+
import itertools
6+
import sys
7+
8+
# Explore itertools.chain()
9+
first_team = ["Sarah", "Matt", "Jim", "Denise", "Kate"]
10+
second_team = ["Mark", "Zara", "Mo", "Jennifer", "Owen"]
11+
12+
for name in itertools.chain(first_team, second_team):
13+
print(name)
14+
15+
# Verify changes in reference counts
16+
print(sys.getrefcount(first_team))
17+
18+
quiz_team = itertools.chain(first_team, second_team)
19+
print(sys.getrefcount(first_team))
20+
21+
for name in quiz_team:
22+
print(name)
23+
24+
print(sys.getrefcount(first_team))
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
Exploring the itertools module
3+
"""
4+
5+
import itertools
6+
7+
numbers = [2, 4, 6, 8, 10]
8+
standard_slice = numbers[1:4]
9+
iterator_slice = itertools.islice(numbers, 1, 4)
10+
11+
# Change third element in numbers
12+
numbers[2] = 999
13+
14+
print(numbers)
15+
16+
print("\nStandard slice:")
17+
for number in standard_slice:
18+
print(number)
19+
20+
print("\nIterator slice:")
21+
for number in iterator_slice:
22+
print(number)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""
2+
Exploring generator expressions
3+
"""
4+
5+
import random
6+
7+
# List comprehension
8+
coin_toss = ["Heads" if random.random() > 0.5 else "Tails" for _ in range(10)]
9+
10+
print(f"List comprehension:\n{coin_toss}")
11+
12+
# Generator expression
13+
coin_toss = ("Heads" if random.random() > 0.5 else "Tails" for _ in range(10))
14+
print(f"\nGenerator expression:\n{coin_toss}")
15+
16+
print(f"\nFirst coin toss: {next(coin_toss)}")
17+
print(f"Second coin toss: {next(coin_toss)}")
18+
19+
# Print remaining coin tosses
20+
for toss_result in coin_toss:
21+
print(toss_result)
22+
23+
# Defining a generator function
24+
25+
26+
def generate_coin_toss(number):
27+
for _ in range(number):
28+
yield "Heads" if random.random() > 0.5 else "Tails"
29+
30+
31+
coin_toss = generate_coin_toss(10)
32+
print("\nUsing a generator function:")
33+
print(next(coin_toss))
34+
print(next(coin_toss))
35+
36+
for toss_result in coin_toss:
37+
print(toss_result)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""
2+
Creating an infinite sequence of elements using generators
3+
"""
4+
5+
import itertools
6+
7+
quarters = itertools.count(start=0, step=0.25)
8+
# Print the first 8 elements, however, the sequence is infinite
9+
for _ in range(8):
10+
print(next(quarters))
11+
12+
names = ["Sarah", "Matt", "Jim", "Denise", "Kate"]
13+
rota = itertools.cycle(names)
14+
print(rota)
15+
16+
print(next(rota))
17+
print(next(rota))
18+
print(next(rota))
19+
20+
21+
# Use a generator function
22+
def generate_rota(iterable):
23+
index = 0
24+
length = len(iterable)
25+
while True:
26+
yield iterable[index]
27+
if index == length - 1:
28+
index = 0
29+
else:
30+
index += 1
31+
32+
33+
rota = generate_rota(names)
34+
print("\nUsing a generator function")
35+
for _ in range(12):
36+
print(next(rota))
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Eager and lazy options for reading a CSV file
3+
"""
4+
5+
import csv
6+
import pprint
7+
8+
print("Eager evaluation using 'open()'")
9+
with open("superhero_pets.csv", encoding="utf-8") as file:
10+
data = file.readlines()
11+
12+
pprint.pprint(data)
13+
14+
print("\nLazy evaluation using 'csv.reader()'")
15+
with open("superhero_pets.csv", encoding="utf-8", newline="") as file:
16+
data = csv.reader(file)
17+
print(data)
18+
19+
print(next(data))
20+
print(next(data))
21+
print(next(data))
22+
23+
for row in data:
24+
print(row)
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Pet Name,Species,Superpower,Favorite Snack,Hero Owner
2+
Whiskertron,Cat,Teleportation,Tuna,Catwoman
3+
Flashpaw,Dog,Super Speed,Peanut Butter,The Flash
4+
Mystique,Squirrel,Illusion,Nuts,Doctor Strange
5+
Quackstorm,Duck,Weather Control,Bread crumbs,Storm
6+
Bark Knight,Dog,Darkness Manipulation,Bacon,Batman
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
"""
2+
Exploring 'enumerate()' lazy evaluation
3+
"""
4+
5+
import random
6+
7+
names = ["Sarah", "Matt", "Jim", "Denise", "Kate"]
8+
random.shuffle(names)
9+
print(names)
10+
11+
# Using `enumerate()` in a 'for' loop
12+
for index, name in enumerate(names, start=1):
13+
print(f"{index}. {name}")
14+
15+
# Using `enumerate()` with 'next()'
16+
numbered_names = enumerate(names, start=1)
17+
print(numbered_names)
18+
19+
print(next(numbered_names))
20+
print(next(numbered_names))
21+
22+
# Update third name
23+
names[2] = "The Coffee Robot"
24+
print(next(numbered_names))
25+
# Output: (3, 'The Coffee Robot')
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
"""
2+
Exploring 'map()' and 'filter()'
3+
"""
4+
5+
original_names = ["Sarah", "Matt", "Jim", "Denise", "Kate", "Andy"]
6+
names = filter(lambda x: ("a" in x) or ("A" in x), original_names)
7+
names = filter(lambda x: len(x) == 4, names)
8+
names = map(str.upper, names)
9+
10+
print(list(names))
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""
2+
Exploring 'zip()' lazy evaluation
3+
"""
4+
5+
import random
6+
7+
names = ["Sarah", "Matt", "Jim", "Denise", "Kate"]
8+
weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]
9+
random.shuffle(names)
10+
print(names)
11+
12+
# Using 'zip()' in a 'for' loop
13+
for day, name in zip(weekdays, names):
14+
print(f"{day}: {name}")
15+
16+
# Using 'zip()' with 'next()'
17+
day_name_pairs = zip(weekdays, names)
18+
print(next(day_name_pairs))
19+
print(next(day_name_pairs))
20+
21+
# Update third name
22+
names[2] = "The Coffee Robot"
23+
print(next(day_name_pairs))
24+
# Output: ('Wednesday', 'The Coffee Robot')

0 commit comments

Comments
 (0)