A “len Python” is an inbuilt function and use for getting the number of items (length) in an object. A len() function can get the length of String, list (Array), tuple, dictionary, etc in Python.
Syntax
The syntax of len() is:
len(object)
Parameters
Object – a sequence (string, bytes, tuple, list, or range) or a collection (dictionary, set, or frozen set)
Return Value
The len() function returns an integer value which is the number of elements in an object.
len() Python example
Let’s see how to get the length of the given string, array, list, tuple, dictionary, etc.
Characters in a string
Find how many characters are in a string.
str1 = "Hello" x = len(str1) print(x)
Output: 5
Count byte
# byte object byte1 = b'Python' print('Length', len(byte1))
Output: Length 6
lists len Python
Example program code of how to get the size of the list(Array) in python using len() function. List indexing starts from 0.
Read more examples:– Python length of a list
list1 = [1, 2, 3] print('length is', len(list1))
Output: length is 3
tuples len Python
Python Tuples are very similar to Lists, the only difference is that tuples are not mutable. See below example of how to get the size of Tuples.
tuple1 = (1, 2, 3) print('length is', len(tuple1))
Output: length is 3
range len Python
A Python Range() Function creates a sequence of the item at one time. Let’s see an example hot find its length.
range1 = range(1, 10) print("The length of the Range is", len(range1))
Output:
The length of the Range is 9
dict len Python
Python dictionary has keys and values. See below code of how to find the length of the dictionary in Python?
dict1 = {'A': 18, 'B': 12, 'C': 22, 'D': 25} print("The length of the Dictionary is", len(dict1))
Output: The length of the Dictionary is 4
len() works with sets
In a Python set, all elements are unique and must be immutable.
See an example of how to get a length of set in python.
set1 = {1, 2, 3} print(len(set1))
Output: 3
Q: How len() works for custom objects?
class Session: def __init__(self, number=0): self.number = number def __len__(self): return self.number # default length is 0 s1 = Session() print(len(s1)) # giving custom length s2 = Session(9) print(len(s2))
Output: 0
9
Do comment if you have any doubts and suggestions on this tutorial. It can be you are interview to how to find the size or length of given data type.
Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code is in Python 3, so it may change its different from python 2 or upgraded versions.