The len() function in Python is used to get the number of items in an object. It is most commonly used with strings, lists, tuples, dictionaries and other iterable or container types. It returns an integer value representing the length or the number of elements. Example:
Python
s = "GeeksforGeeks"
# Get length of the string
l = len(s)
print(l)
Explanation: The string "GeeksforGeeks" has 13 characters. The len() function counts and returns this number.
Syntax of len() function
len(object)
Parameter: object is a sequence (such as a string, list, tuple) or collection (such as a dictionary, set) whose length is to be calculated.
Returns: An integer value indicating the number of items in the object.
Examples of using len() function
Example 1: In this example, we are getting the length of a list, tuple and dictionary and printing the result for each.
Python
a = ['geeks', 'for', 'geeks', 2022]
print(len(a)) # List length
b = (1, 2, 3, 4)
print(len(b)) # Tuple length
c = {"name": "Alice", "age": 30, "city": "New York"}
print(len(c)) # Dict keys
Explanation:
- For the list a, len(a) returns 4 because it contains four items.
- For the tuple b, len(b) also returns 4 as there are four elements.
- For the dictionary c, len(c) returns 3 because it counts the number of key-value pairs (i.e., keys).
Example 2: In this example, we are getting the length of an empty list and printing the result.
Python
a = []
# Get the length of the empty list
print(len(a))
Explanation: Since the list is empty, len() returns 0, indicating there are no elements inside it.
Example 3: In this example, we are using len() along with a for loop to access and print each element of a list by its index.
Python
a = [10, 20, 30, 40, 50]
# Iterate over list
for i in range(len(a)):
print("Index:", i, "Value:", a[i])
OutputIndex: 0 Value: 10
Index: 1 Value: 20
Index: 2 Value: 30
Index: 3 Value: 40
Index: 4 Value: 50
Explanation: In this example, range() and len() are used to iterate over the list a by index. len(a) gives the total number of elements and range(len(a)) provides the index sequence. In each iteration, a[i] accesses the value at index i.
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice