For working professionals
For fresh graduates
More
13. Print In Python
15. Python for Loop
19. Break in Python
23. Float in Python
25. List in Python
27. Tuples in Python
29. Set in Python
53. Python Modules
57. Python Packages
59. Class in Python
61. Object in Python
73. JSON Python
79. Python Threading
84. Map in Python
85. Filter in Python
86. Eval in Python
96. Sort in Python
101. Datetime Python
103. 2D Array in Python
104. Abs in Python
105. Advantages of Python
107. Append in Python
110. Assert in Python
113. Bool in Python
115. chr in Python
118. Count in python
119. Counter in Python
121. Datetime in Python
122. Extend in Python
123. F-string in Python
125. Format in Python
131. Index in Python
132. Interface in Python
134. Isalpha in Python
136. Iterator in Python
137. Join in Python
140. Literals in Python
141. Matplotlib
144. Modulus in Python
147. OpenCV Python
149. ord in Python
150. Palindrome in Python
151. Pass in Python
156. Python Arrays
158. Python Frameworks
160. Python IDE
164. Python PIP
165. Python Seaborn
166. Python Slicing
168. Queue in Python
169. Replace in Python
173. Stack in Python
174. scikit-learn
175. Selenium with Python
176. Self in Python
177. Sleep in Python
179. Split in Python
184. Strip in Python
185. Subprocess in Python
186. Substring in Python
195. What is Pygame
197. XOR in Python
198. Yield in Python
199. Zip in Python
The len() function in Python is a built-in function for determining the length of an object such as a string, list, or tuple. It returns the number of items in the object.
Often, when working with lists or strings, you may need to determine how many elements or characters they contain. Without a straightforward way to find this, your code can get complicated and less efficient.
Thankfully, the len() function is here to make it easy! With just one line of code, you can find the length of any iterable object.
By the end of this guide, you'll know exactly how to use len() python examples in different situations. This will help you write cleaner, more effective Python code.
Let’s get started!
"Boost your Python skills with our Data Science and Machine Learning courses from top universities — take the next step in your learning journey today!"
Whether you're working with a string, list, tuple, or even a dictionary, the len() function helps you quickly find how many items are inside. It’s a handy tool for keeping track of the size of data structures in your code.
For example, if you're working with a list of items, you might need to know how many elements are in the list. Instead of manually counting them, you can simply use the len() function to return the total count.
This makes your code more efficient and easier to maintain.
Syntax of len() Function in Python
len(object)
If you're enjoying learning about Python and ready to dive deeper into software development, consider exploring our Online Software Development Courses. It can help you further enhance your knowledge and take your coding skills to the next level!
The len() function in Python list is extremely versatile and can be used with various data structures, including lists, tuples, and dictionaries.
Let's start with a list. A list is an ordered collection of elements, and the len() function in python list can be used to count how many items are in it.
For example, suppose you have a list of students in a class:
students = ["Anil", "Sam", "Priya", "Yash"]
#get the length of the list
num_students = len(students)
print(num_students)
Output:
4
Explanation:
Now let’s look at a tuple. A tuple is similar to a list but is immutable, meaning its contents cannot be changed after creation.
Here's an example with a tuple of numbers:
numbers = (10, 20, 30, 40, 50)
#get the length of the tuple
num_numbers = len(numbers)
print(num_numbers)
Output:
5
Explanation:
Finally, let's explore how len() works with a dictionary. A dictionary is a collection of key-value pairs. In this case, len() will return the number of key-value pairs in the dictionary.
person = {"name": "Parth", "age": 45, "city": "Gurgaon"}
#get the length of the dictionary
num_keys = len(person)
print(num_keys)
Output:
3
Explanation:
Also Read: List vs Tuple: Understanding the Differences in Python
You can also use len() with custom objects by defining the special method __len__() in your class. This method should return an integer value representing the size or length of the object.
Let’s create a custom class and implement __len__().
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __len__(self):
return self.pages #return the number of pages as the length of the book
#create a Book object
my_book = Book("Python Programming", 350)
#use len() on the custom object
book_length = len(my_book)
print(book_length)
Output:
350
Explanation:
This is a great example of how the len() function can be applied to custom objects. It can be really useful when you want to give your objects a sense of "size" or "length" and make them compatible with Python's In-built functions like len().
“Start your coding journey with our complimentary Python courses designed just for you — dive into Python programming fundamentals, explore key Python libraries, and engage with practical case studies!”
When you use the len() function on an empty object, the result is always 0. This is because an empty object doesn’t contain any elements for the len() function to count.
Here’s how the len() function behaves when called on an empty list:
#create an empty list
empty_list = []
#call len() on the empty list
list_length = len(empty_list)
print(list_length) #this will print 0
Output:
0
Explanation:
Now, let’s try modifying the list by adding a few items to understand how len() dynamically updates the count:
#add elements to the list
empty_list.append("Python")
empty_list.append("Tutorial")
list_length = len(empty_list)
print(list_length) #this will print 2
Output:
2
Explanation:
For example, before processing data, you might want to confirm that a list or dictionary contains elements. Using len() is an efficient way to do this.
This behavior remains consistent with all iterable objects, making len() a reliable tool for such checks.
Using the len() function in a Python for loop allows you to iterate through a collection and perform operations on its elements based on its length. This approach is useful when you need to access elements using their index or dynamically control loop iterations.
Let’s break this down with an example:
#define a list of programming languages
languages = ["Python", "Java", "C++", "JavaScript"]
#use len() in a for loop to iterate based on index
for i in range(len(languages)):
#access and print each element using its index
print(f"Language at index {i}: {languages[i]}")
Output:
mathematica
Language at index 0: Python
Language at index 1: Java
Language at index 2: C++
Language at index 3: JavaScript
Explanation:
Let’s take it a step further. Suppose you want to find and print the names of programming languages that have more than 4 characters:
#use len() in a loop with a condition
for i in range(len(languages)):
if len(languages[i]) > 4: #check the length of each language name
print(f"{languages[i]} has more than 4 characters.")
Output:
Python has more than 4 characters.JavaScript has more than 4 characters.
Explanation:
This len() python example showcases how the function enhances the utility of a for loop, especially when working with collections like lists.
Also Read: Conditional Statements in Python: If, If else, Elif, Nested if Statements
Let’s explore these scenarios and see how to handle them effectively.
The len() function works only with iterable objects such as lists, strings, tuples, and dictionaries. Using it on a non-iterable object, such as an integer, will raise a TypeError.
Example:
#trying to use len() on an integer
number = 12345
try:
print(len(number)) #this will raise an error
except TypeError as e:
print(f"Error: {e}")
Output:
Error: object of type 'int' has no len()
The len() function requires custom objects to implement the __len__() method. If the method is not defined, a TypeError is raised.
Example:
#custom class without __len__ method
class MyClass:
pass
my_object = MyClass()
try:
print(len(my_object)) #this will raise an error
except TypeError as e:
print(f"Error: {e}")
Output:
Error: object of type 'MyClass' has no len()
Calling len() on a variable that has not been initialized results in a NameError.
Example:
try:
print(len(uninitialized_variable)) #variable is not defined
except NameError as e:
print(f"Error: {e}")
Output:
Error: name 'uninitialized_variable' is not defined
The len() function does not work directly on generators or iterators in Python because they don’t store elements in memory.
Example:
#generator expression
generator = (x for x in range(10))
try:
print(len(generator)) #this will raise an error
except TypeError as e:
print(f"Error: {e}")
Output:
Error: object of type 'generator' has no len()
Keep practicing different functions and methods in Python, and you'll gradually build confidence and mastery over the language.
The len() function in Python determines the total number of elements in an iterable, such as a list, string, tuple, or dictionary. It’s a versatile tool often demonstrated through len() Python example.
Yes, but len() only counts the top-level elements in a nested list. It doesn't dive into the inner lists unless specified through additional logic. For example, len() function in Python list will count nested lists as single elements.
When used on a string, len() returns the number of characters in the string, including spaces and special characters. This makes it ideal for len() Python example with text data.
Absolutely! The len() function can count the number of unique elements in a set, making it helpful when working with collections of distinct items.
No, len() cannot directly determine the size of generator objects since they are iterators and don’t store their elements in memory.
Yes, you can override len() by defining a __len__() method in your class. This allows custom objects to return specific sizes when len() Python example are explored with user-defined classes.
The len() function is a built-in function, not a method. Unlike methods, it operates independently of the object on which it's called.
When used on dictionaries, len() returns the count of key-value pairs. It’s a common use case in len() Python example for working with key-based data.
No, len() only takes one argument. Passing more than one argument will raise a TypeError.
Yes, the len() function works seamlessly with empty collections, returning 0. This makes it useful in len() Python example that handle edge cases.
While len() is the most straightforward way, you can also use libraries like NumPy for advanced size calculations, especially for arrays and multi-dimensional data.
Take our Free Quiz on Python
Answer quick questions and assess your Python knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.