Python Len() - Programiz
Maybe your like
The len() function returns the length (the number of items) of an object.
Example
languages = ['Python', 'Java', 'JavaScript'] length = len(languages) print(length) # Output: 3len() Syntax
The syntax of len() is:
len(s)len() Argument
The len() function takes a single object as argument. It can be:
- Sequence - list, tuple, string, range, etc.
- Collection - set, dictionary etc.
len() Return Value
It returns an integer (the length of the object).
Example 1: Working of len() with Tuples, Lists and Range
x = [1, 2, 3] print(len(x)) # Output: 3 y = (1, 2, 3) print(len(y)) # Output: 3 z = range(8, 20, 3) print(len(z)) # Output: 4Visit these pages to learn more about:
- Python range()
- Python Lists
- Python Tuples
Example 2: len() with Strings, Dictionaries and Sets
text = 'Python' print(len(text)) # Output: 6 person = {"name": 'Amanda', "age": 21} print(len(person)) # Output: 2 animals = {'tiger', 'lion', 'tiger', 'cat'} print(len(animals)) # Output: 3Visit these pages to learn more about:
- Python Strings
- Python Dictionaries
- Python Sets
len() with User-defined Objects
The len() function internally calls the object's __len__() method. You can think of len() as:
def len(s): return s.__len__()Therefore, we can make len() work for a user-defined object by implementing the ___len___() method.
Example 3: len() with User-defined Object
class Session: def __init__(self, number = 0): self.number = number def __len__(self): return self.number # default length is 0 session1 = Session() print(len(session1)) # Output: 0 session2 = Session(6) print(len(session2)) # Output: 6Tag » What Does Len Do In Python
-
Using The Len() Function In Python
-
Python Len() Function - W3Schools
-
A Step-By-Step Guide To Len Python | Career Karma
-
Python String Length | Len() - GeeksforGeeks
-
Python Len() Function: How To Find Length Of The String - Guru99
-
Python Len() Method (With Examples) - TutorialsTeacher
-
What Is Len() In Python? How To Use The Len() Function To Find The ...
-
Introduction To Python's Len() Function - YouTube
-
What Does The Len() Function Do In Python? - Quora
-
What Is Python Len() Function Used For? - Toppr
-
Python List Len() Method - Tutorialspoint
-
What Does Len() Mean In Python, And What Is The Difference Between ...
-
Len() Function In Python - Scaler Topics
-
Python String Length | Len() Method With Example - STechies