The Wayback Machine - https://web.archive.org/web/20250323002825/https://www.geeksforgeeks.org/python-len-function/
Open In App

Python len() Function

Last Updated : 25 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

Python
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.

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.

Python
# 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.

Python
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.

Python
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])







Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg