Understanding Python's len() Function

Apr 24, 2025

Python len() Function Reference on W3Schools

Overview

Definition and Usage

  • Function: len()
  • Purpose: Returns the number of items in a sequence or collection.
  • When used on a string, it returns the number of characters.

Syntax

len(object)
  • Parameter:
    • object: Required. The object can be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Examples

  • Example 1: Number of items in a list
    mylist = ["apple", "banana", "cherry"]
    x = len(mylist)
    
  • Example 2: Number of characters in a string
    mystring = "Hello"
    x = len(mystring)
    

Additional Resources

  • Users are encouraged to try the examples on their own Python server.
  • For more examples and practice, users can visit the W3Schools TryPython page.

Related Topics

Learning and Certification

  • W3Schools provides various tutorials and exercises to test Python knowledge.
  • Certification is available for those who want to document their Python skills.
  • Sign Up for tracking progress and accessing exclusive content.