Python built-in function len

Source: Internet
Author: User
English documents:

Len (s)

Return the length (the number of items) of an object. The argument may is a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set , or frozen set).

Description

1. Returns the length of an object, which can be a sequence (such as a string, byte array, tuple, list, and Range object), or a collection (such as a dictionary, collection, immutable collection)

>>> len (' ABCD ') # string >>> len (bytes (' ABCD ', ' Utf-8 ')) # byte array >>> len ((1,2,3,4)) # tuple >> > len ([1,2,3,4]) # list >>> len (range 1,5) # Range object >>> len ({' A ': 1, ' B ': 2, ' C ': 3, ' d ': 4}) # dictionary >>& Gt Len ({' A ', ' B ', ' C ', ' d '}) # collection >>> len (Frozenset (' ABCD ')) #不可变集合

2. If the parameter is a different type, it must implement the __len__ method and return an integer, otherwise an error.

>>> class A:    def __init__ (self,name):        self.name = name    def __len__ (self):        return Len ( Self.name) >>> a = A (") >>> Len (a) >>> a = A (' Aim ') >>> Len (a) >>> class B:    pass>>> B = B () >>> Len (b) Traceback (most recent call last):  File "
 
  
   
  ", line 1, in 
  
   
    
       len (b) Typeerror:object of type ' B ' have no Len () >>> class C:
    def __len__ (self):        return ' len ' >>> C = C () >>> Len (c) Traceback (most recent call last):  File "
   
    
     
    ", line 1, in 
    
     
      
         len (c) TypeError: ' str ' object cannot is interpreted as an INTEGER
      
     
   
    
  
   
 
  
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.