Can you explain the concept of generators in Python and provide an example of how they can be used?
Certainly. Generators in Python are a simple way to create iterators using functions. They allow you to iterate through a potentially large set of data efficiently by generating values on-the-fly, rather than storing everything in memory. Here's an example of a generator function that yields squares of numbers:
def generate_squares(n):
for i in range(n):
yield i * i
# Usage
squares_generator = generate_squares(5)
for square in squares_generator:
print(square)