Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
Now Reading
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
In this tutorial, we will deep-dive into the len function in Python, a versatile built-in utility. Essential for both beginners and seasoned developers, the len function in Python is instrumental in determining the size of various data structures, whether it's a simple string, a list, or more complex types. Let's unravel its functionalities and best practices.
The len function in Python stands out as a fundamental tool for measuring the length or size of multiple data types. Its applications span across strings, lists, tuples, and even dictionaries, marking its importance in day-to-day coding tasks and larger-scale projects.
The len() function in Python is used to quickly determine the length or the number of items in a collection, such as a string, list, tuple, dictionary, or any other iterable object. It returns an integer representing the length of the given object. The len() function allows developers to make informed decisions and perform appropriate operations based on the size of the collections.
Here is the syntax of len() function:
len(object)
In the above syntax,
object: The collection or iterable object for which you want to determine the length.
Let us learn how to use the len() function with the help of some examples.
Code:
text = "Hello, World!"
length = len(text)
print(length) # Output: 13
In this example, len(text) returns 13, as there are 13 characters in the string "Hello, World!".
Code:
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # Output: 5
Here, len(my_list) returns 5, indicating that the list my_list contains 5 elements.
Code:
my_tuple = (10, 20, 30, 40, 50)
length = len(my_tuple)
print(length) # Output: 5
Similarly, len(my_tuple) returns 5, signifying that the tuple my_tuple consists of 5 elements.
Code:
my_dict = {'a': 1, 'b': 2, 'c': 3}
length = len(my_dict)
print(length) # Output: 3
In this case, len(my_dict) returns 3, which corresponds to the number of key-value pairs in the dictionary my_dict.
In most cases, len() is safe to use with built-in Python data structures, but when working with custom classes or non-iterable objects, you should handle potential exceptions or define the behavior using the __len__() method for custom classes. The len() function typically does not raise exceptions for built-in Python data structures like strings, lists, tuples, and dictionaries.
However, there are some scenarios where len() can raise exceptions:
Example:
class MyCustomClass:
def __init__(self):
self.data = [1, 2, 3]
obj = MyCustomClass()
length = len(obj) # Raises TypeError: object of type 'MyCustomClass' has no len()
Example:
number = 42
length = len(number) # Raises TypeError: object of type 'int' has no len()
Certainly, let's explore the usage of the len() function with various Python data structures, including built-in sequences, collections, other data types, third-party libraries, and user-defined classes, along with advanced code examples.
my_list = [1, 2, 3, 4, 5]
list_length = len(my_list) # Returns 5
my_tuple = (10, 20, 30, 40, 50)
tuple_length = len(my_tuple) # Returns 5
text = "Hello, World!"
string_length = len(text) # Returns 13
my_dict = {'a': 1, 'b': 2, 'c': 3}
dict_length = len(my_dict) # Returns 3
my_set = {10, 20, 30, 40, 50}
set_length = len(my_set) # Returns 5
number = 42
try:
length = len(number) # Raises TypeError: object of type 'int' has no len()
except TypeError as e:
print(f"Error: {e}")
# Using len() with NumPy arrays
import numpy as np
my_array = np.array([1, 2, 3, 4, 5])
array_length = len(my_array) # Returns 5
# Using len() with Pandas DataFrames
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 30, 35]}
df = pd.DataFrame(data)
df_length = len(df) # Returns 3 (number of rows)
class MyCustomClass:
def __init__(self, data):
self.data = data
def __len__(self):
return len(self.data)
my_obj = MyCustomClass([1, 2, 3, 4, 5])
custom_length = len(my_obj) # Returns 5 (custom implementation)
In this example, the MyCustomClass class defines a custom __len__() method, allowing the len() function to work with instances of this class.
Let's explore an advanced len() Python example by creating a program that calculates the length of sequences within a list and then performs customized operations based on those lengths. In this example, we'll use a list of words, and we'll categorize the words into different groups based on their lengths.
Code:
# Define a list of words
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "kiwi", "lemon", "mango"]
# Initialize empty dictionaries to categorize words by length
word_groups = {}
# Calculate the length of each word and categorize them
for word in words:
length = len(word)
# Check if a group for this length exists, create it if not
if length not in word_groups:
word_groups[length] = []
# Append the word to its respective group
word_groups[length].append(word)
# Print the categorized words
for length, group in word_groups.items():
if length == 1:
print(f"Single-letter words: {', '.join(group)}")
else:
print(f"Words with length {length}: {', '.join(group)}")
In this program, we start with a list of words. We use the len() function to calculate the length of each word, and then we categorize the words into dictionaries based on their lengths. The keys in the word_groups dictionary represent word lengths, and the values are lists of words with those lengths.
We iterate through the list of words, and for each word, we calculate its length. If a group for that length does not yet exist in the word_groups dictionary, we create it. We then append the word to its respective group.
Finally, we print the categorized words. If the length is 1, we print them as single-letter words; otherwise, we display words grouped by their lengths.
The len() function in Python offers several advantages when used in programming. These advantages contribute to code clarity, efficiency, and flexibility, making it a valuable tool in various scenarios.
Here are the key advantages of using the len() function:
Example:
my_list = [1, 2, 3, 4, 5]
for i in range(len(my_list)):
print(my_list[i])
The len function in Python isn't just about counting characters or list items. It's about efficient code, optimizing operations, and enhancing readability. As we've journeyed through its varied applications and nuances, it's evident that mastering this function is key to solidifying one's Python foundations.
If you're looking to further elevate your Python prowess, consider the advanced courses offered by upGrad, ensuring you stay at the forefront of coding excellence.
The len() function works directly on lists to count items. However, for arrays, especially when using libraries like numPy, dimension specifics are essential.
Iterative methods or specific string properties can be employed for this purpose.
Yes, you can seamlessly integrate len() within user-defined functions for diverse functionalities.
The if len(Python_object) construct in Python checks if the specified object (like a list or string) has a non-zero length, executing the subsequent code block if true.
Typically, len() is efficient. However, for significantly large data structures, alternate optimization techniques might be more suitable.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...