How do you turn a function into a generator in Python? Which list method removes an element?
💡 Model Answer
In Python, a function becomes a generator when it contains the keyword yield. When the function is called, it returns a generator object that can be iterated over; each time the generator’s __next__() method is called, execution runs until the next yield statement, returning the yielded value. Example:
def count_up_to(n):
i = 0
while i < n:
yield i
i += 1Calling count_up_to(5) gives a generator that yields 0,1,2,3,4.
To remove an element from a list, you can use list.remove(value) which removes the first occurrence of the specified value, or list.pop(index) which removes and returns the element at the given index. Both operations have O(n) time complexity because they may need to shift elements.
remove() is used when you know the value, while pop() is used when you know the position.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500