Python len() Function
len() function returns number of items in an object that can be characters, words, or elements in a sequence.
Let’s start with a simple example to understand the len() functions with strings:
s = "GeeksforGeeks"
# Use len() to find the length of the string
length = len(s)
print(length)
Output
13
Note: When object is string, len() function will return number of characters.
Table of Content
Syntax: len(Object)
Parameter: Object of which we have to find the length for example tuple, string, list, etc.
Returns: len() function returns an integer value, which represents the number of items present in the object.
Using len() with List, Tuple, Dictionary
len() function is frequently used to determine the length or number of elements of any iterables.
# Using len() in list
list1 = ['geeks', 'for', 'geeks', 2022]
print(len(list1))
# Using len() in tuple
tuple1 = (1,2,3,4)
print(len(tuple1))
# Using len() in dictionary
d1 = {"name": "Alice", "age": 30, "city": "New York"}
print(len(d1))
Output
4 4 3
Explanation: In the above code we using len() to get the length of the various iterables like – List, Tuples and Dictionary.
What happens when len() is called on empty objects ?
When len() is called on empty objects, it return 0. This is because the length of an object will be empty.
empty_list = []
# Print the length of the empty list
print(len(empty_list))
Output
0 0
Using len() function with For Loop
We can use len() and for loop to access each element by index.
a = [10, 20, 30, 40, 50]
# Use len() to get the length of the list
for i in range(len(a)):
print("Index:", i, "Value:", a[i])
Enhance your coding skills with DSA Python, a comprehensive course focused on Data Structures and Algorithms using Python. Over 90 days, you'll explore essential algorithms, learn how to solve complex problems, and sharpen your Python programming skills. This course is perfect for anyone looking to level up their coding abilities and get ready for top tech interviews.
Join the Three 90 Challenge and commit to completing 90% of the course in 90 days to earn a 90% refund. It’s the perfect way to stay focused, track your progress, and reap the rewards of your hard work. Take the challenge and become a DSA expert in Python today


