Python len() Built in Function
The len() function returns the number of items in an object. It can be used with different data types such as strings, lists, tuples, dictionaries, sets, etc.
Here are some examples of using the len() function:
# Example 1: Get the length of a string
name = "Alice"
length = len(name)
print(length) # 5
# Example 2: Get the length of a list
fruits = ["apple", "banana", "cherry"]
length = len(fruits)
print(length) # 3
# Example 3: Get the length of a tuple
colors = ("red", "green", "blue")
length = len(colors)
print(length) # 3
# Example 4: Get the length of a dictionary
person = {"name": "Bob", "age": 25, "gender": "male"}
length = len(person)
print(length) # 3
# Example 5: Get the length of a set
numbers = {1, 2, 3, 4}
length = len(numbers)
print(length) # 4
If you have any questions about this code, you can drop a line in comment.
Comments
Post a Comment