PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Medium

Question 35

The iterator protocol is a way in which an object should behave to conform to the rules imposed by the context of the for and in statements. An object conforming to the iterator protocol is called an iterator. An iterator must provide two methods: (Select two)

  • A

    __next__() which is intended to return the next value of the desired series. If there are no more values to provide, the method should raise the StopIteration exception.

  • B

    __contains__() which checks if an item is present in the collection.

  • C

    __init__() which should return the object itself and which is invoked once.

  • D

    __repr__() which should be a formal representation of a Python object.

  • E

    __iter__() which should return the object itself and which is invoked once.

Reveal correct answers

Correct answers: A, E

A.

This is correct. The __next__() method is also part of the iterator protocol. It returns the next value in the sequence and raises StopIteration when there are no more values.

B.

The __contains__() method is used for membership tests and checks if an item is in a collection (e.g., a list or set). It is not part of the iterator protocol.

C.

This is incorrect. The __init__() method is a constructor used to initialize a new object. It is not a part of the iterator protocol and does not have any role in the iteration process.

D.

This is incorrect. The __repr__() method provides a string representation of an object, useful for debugging and development, but it is not related to the iterator protocol.

E.

This is correct. The __iter__() method is a part of the iterator protocol and should return the iterator object itself. This method is called once at the beginning of iteration.

Discussion

Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.

You must be logged in to post a comment.

Preparing For

Your Certification?

255+ certifications
Detailed explanations
Free PDF samples

Has All The Questions You Need