Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python __repr__() magic method
Next article icon

Python __len__() magic method

Last Updated : 26 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Python __len__ is one of the various magic methods in Python programming language, it is basically used to implement the len() function in Python because whenever we call the len() function then internally __len__ magic method is called. It finally returns an integer value that is greater than or equal to zero as it represents the length of the object for which it is called. 

Python __len__() Function Syntax

Syntax: object.__len__()

  • object: It is the object whose length is to be determined.                 

Returns: Returns a non negative integer.

Python __len__() Function Example

When the object we are iterating already has  __len__ method defined internally, then len function gives the correct result for the object i.e.

Python3




class GFG:
    def __init__(self, a):
        self.a = a
    def __len__(self):
        return len(self.a)
       
obj = GFG("GeeksForGeeks")
print(len(obj))
 
 

Output:

13

Example 2:

When the object doesn’t have a predefined __len__ method, then while executing the len function it gives a TypeError, but it can be corrected by defining a __len__ method by our own,

Python3




class GFG:
   
    def __init__(self, item):
        self.item = item
    def __len__(self):
        return 1
 
obj = GFG("Geeksforgeeks")
print(obj.__len__())
 
 

Output:

1

Default __len__() Implementation

When we call len(obj) from the class without defining __len__() methods then it will raise a TypeError: object of type ‘…’ has no len().

Python3




class Length:
    pass
     
obj = Length()
print(len(obj))
 
 

Output:

TypeError                                 Traceback (most recent call last) <ipython-input-9-c08d3a505e12> in <module>      3       4 obj = Length() ----> 5 print(len(obj)) TypeError: object of type 'Length' has no len()


Next Article
Python __repr__() magic method

S

shlokdi35dq
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • Python __add__() magic method
    Python __add__() function is one of the magic methods in Python that returns a new object(third) i.e. the addition of the other two objects. It implements the addition operator "+" in Python. Python __add__() Syntax Syntax: obj1.__add__(self, obj2) obj1: First object to add in the second object.obj2
    1 min read
  • Python __repr__() magic method
    Python __repr__() is one of the magic methods that returns a printable representation of an object in Python that can be customized or predefined, i.e. we can also create the string representation of the object according to our needs. Python __repr__() magic method Syntax Syntax: object.__repr__() o
    4 min read
  • Python List max() Method
    max() function in Python is a built-in function that finds and returns the largest element from the list. Let's understand it better with an example: [GFGTABS] Python a = [2,3,6,1,8,4,9,0] print(max(a)) [/GFGTABS]Output9 Syntaxmax(listname) Parameter: listname : Name of list in which we have to find
    4 min read
  • Dunder or magic methods in Python
    Python Magic methods are the methods starting and ending with double underscores '__'. They are defined by built-in classes in Python and commonly used for operator overloading.  They are also called Dunder methods, Dunder here means "Double Under (Underscores)". Python Magic MethodsBuilt in classes
    7 min read
  • Python List methods
    Python list methods are built-in functions that allow us to perform various operations on lists, such as adding, removing, or modifying elements. In this article, we’ll explore all Python list methods with a simple example. List MethodsLet's look at different list methods in Python: append(): Adds a
    3 min read
  • Python | Decimal max() method
    Decimal#max() : max() is a Decimal class method which compares the two Decimal values and return the max of two. Syntax: Decimal.max() Parameter: Decimal values Return: the max of two. Code #1 : Example for max() method # Python Program explaining # max() method # loading decimal library from decima
    2 min read
  • Python | Decimal logical_and() method
    Decimal#logical_and() : logical_and() is a Decimal class method which returns the digit-wise and of the two (logical) Decimal values. Syntax: Decimal.logical_and() Parameter: Decimal values Return: the digit-wise and of the two (logical) Decimal values. Code #1 : Example for logical_and() method # P
    2 min read
  • Python | Decimal max_mag() method
    Decimal#max_mag() : max_mag() is a Decimal class method which compares the two Decimal values and return the max of two, with their sign ignored. Syntax: Decimal.max_mag() Parameter: Decimal values Return: the max_mag of two, with their sign ignored. Code #1 : Example for max_mag() method # Python P
    2 min read
  • Python hash() method
    Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary. Python hash() function SyntaxSyntax : hash(obj) Parameters : obj : The object which we need
    6 min read
  • expandtabs() method in Python
    expandtabs() method in Python is used to replace all tab characters (\t) in a string with spaces. This method allows for customizable spacing, as we can specify the number of spaces for each tab. It is especially useful when formatting text for better readability or alignment. Let's understand with
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences