×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Python len() Function: Use, Syntax, and Examples

By IncludeHelp Last updated : December 07, 2024

Python len() function

The len() function is a library function in Python, it is used to get the length of an object (the object may a string, list, tuple, etc). It accepts an object and returns its length (total number of characters in case of a string, the total number of elements in case of an iterable).

Syntax

The following is the syntax of len() function:

len(object)

Parameter(s):

The following are the parameter(s):

  • object – An object like string, list etc whose length to be calculated.

Return Value

The return type of len() function is <class 'int'>, it returns length of the object.

Example 1: Find the length of a string

x = "Hello, world!"
print("Length of", x, "is", len(x))

x = "This a simple program"
print("Length of", x, "is", len(x))

Output

Length of Hello, world! is 13
Length of This a simple program is 21

Example 2: Find the length of a list

x = [10, 20, 30]
print("Length of", x, "is", len(x))

x = [101, "Hell0", 30, 50]
print("Length of", x, "is", len(x))

Output

Length of [10, 20, 30] is 3
Length of [101, 'Hell0', 30, 50] is 4

Example 3: Find the length of a tuple

x = ("New Delhi", "Indore", "Banglore")
print("Length of", x, "is", len(x))

x = ()
print("Length of", x, "is", len(x))

Output

Length of ('New Delhi', 'Indore', 'Banglore') is 3
Length of () is 0

Example 4: Find the length of a dictionary

# Creating  dictionary
alphabets = {"a": "apple", "b": "ball", "c": "cat", "d": "dog"}

# Printing the dictionary
print("alphabets:", alphabets)

# Length of the dictionary
print("The total elements are:", len(alphabets))

Output

alphabets: {'a': 'apple', 'b': 'ball', 'c': 'cat', 'd': 'dog'}
The total elements are: 4


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.