LearnFrenzy
Sign in Take a free test

OOP in Python · Predict the Output · Question 14

__len__ and __contains__ Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 14 Back to Exercise

What is the output of the following Python program?

main.py
class Playlist:
    def __init__(self, *songs):
        self.songs = list(songs)
    def __len__(self):
        return len(self.songs)
    def __contains__(self, song):
        return song.lower() in (s.lower() for s in self.songs)

p = Playlist("Believer", "Kesariya", "Levitating")
print(len(p), "kesariya" in p, "Perfect" in p, bool(Playlist()))
  • A 3 False False True
  • B 3 True False True
  • C 3 True False False Correct
  • D TypeError
Correct Answer: Option C

in calls __contains__ (case-insensitive here). An object whose __len__ returns 0 is falsy.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links