# Demonstrating several ways to build a list containing a range of numbers.
# Each function shows a different style that experienced developers commonly use.
# Build a list using the built‑in range() constructor.
# This is the most direct and widely used approach.
def make_range_builtin(start, end):
# range() produces a lazy sequence; list() materializes it.
return list(range(start, end))
# Build a list using a list comprehension.
# This is expressive and works well when transforming values.
def make_range_comprehension(start, end):
# Generates numbers from start to end‑1.
return [n for n in range(start, end)]
# Build a list using a generator expression and list().
# Useful when you want to keep the expression flexible.
def make_range_generator(start, end):
return list(n for n in range(start, end))
# Build a list using a manual loop.
# Clear and explicit; helpful when adding logic inside the loop.
def make_range_loop(start, end):
values = []
for n in range(start, end):
values.append(n)
return values
# Build a list using itertools.count.
# count() is an infinite sequence, so we stop manually.
from itertools import count
def make_range_itertools(start, end):
values = []
for n in count(start):
if n >= end:
break
values.append(n)
return values
# Display a list for demonstration.
def show(label, values):
print(f"{label}: {values}")
def main():
# Build lists using all approaches.
a = make_range_builtin(1, 10)
b = make_range_comprehension(1, 10)
c = make_range_generator(1, 10)
d = make_range_loop(1, 10)
e = make_range_itertools(1, 10)
# Show results.
show("builtin range()", a)
show("list comprehension", b)
show("generator expression", c)
show("manual loop", d)
show("itertools.count", e)
if __name__ == "__main__":
main()
"""
run:
builtin range(): [1, 2, 3, 4, 5, 6, 7, 8, 9]
list comprehension: [1, 2, 3, 4, 5, 6, 7, 8, 9]
generator expression: [1, 2, 3, 4, 5, 6, 7, 8, 9]
manual loop: [1, 2, 3, 4, 5, 6, 7, 8, 9]
itertools.count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
"""