Python built-in function len

Source: Internet
Author: User
Python built-in function len English document:

Len (s)

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

Note:

1. the length of the returned object. parameters can be sequences (such as strings, byte arrays, tuples, lists, and range objects), or collections (such as dictionaries, sets, and immutable sets)

>>> Len ('ABCD') # string >>> len (bytes ('abcd', 'utf-8') # byte array >>> len, (3, 4) # tuples >>> len ([, 3, 4]) # List >>> len (range )) # range object >>> len ({'a': 1, 'B': 2, 'C': 3, 'D': 4 }) # Dictionary >>> len ({'a', 'B', 'c', 'D'}) # set >>> len (frozenset ('ABCD ')) # immutable set

2. if the parameter is of another type, it must implement the _ len _ method and return an integer. Otherwise, an error is returned.

>>> 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' has 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 be 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.