Cognizant interview question

What are iterators,generators and decorators?

Interview Answer

Anonymous

Nov 17, 2024

Iterators Objects that use the next() method to get the next value in a sequence. To implement an iterator, you need to create an __iter__() and __next__() method. Generators Functions that use a yield statement to produce a sequence of values. Generators use lazy evaluation, so they don't load all values at once. You can implement a generator using the yield keyword in a Python function or comprehension. Decorators Allow you to add functionality before and/or after a function executes. You can use decorators to separate concerns and write reusable code blocks.