Junior — Middle
Can you give an example of using a generator in practice?
sobes.tech AI
Answer from AI
Generators in Python allow creating iterators that return values one by one, saving memory and enabling working with large or infinite sequences.
A practical example is reading a large file line by line:
def read_large_file(file_path):
with open(file_path, 'r') as file:
for line in file:
yield line.strip()
for line in read_large_file('big_log.txt'):
process(line) # process each line
Here, the read_large_file function is a generator that returns lines of the file one at a time, without loading the entire file into memory at once. This is convenient and efficient when working with large data.