⬅ Previous Topic
Python iter() Function – Create an Iterator from IterableNext Topic ⮕
Python list() Function – Convert Data to a List⬅ Previous Topic
Python iter() Function – Create an Iterator from IterableNext Topic ⮕
Python list() Function – Convert Data to a Listlen()
FunctionThe len() function in Python is used to get the number of items in an object. It works with many data types like strings, lists, tuples, dictionaries, and more.
len(object)
object
– A sequence (like string, list, tuple) or a collection (like dictionary, set, etc.).text = "Hello, World!"
print(len(text))
13
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
5
values = (10, 20, 30)
print(len(values))
3
person = {"name": "Alice", "age": 25, "city": "New York"}
print(len(person))
3
Note: len()
returns the number of keys in the dictionary.
__len__()
methodlen()
Useful?if len(my_list) == 0:
len(5)
→ Raises TypeError
because int
has no lengthlen()
is often used in interview coding problems to control loops, check constraints, or validate data. Know which data types it works on!
len()
returns the number of items in an objectTypeError
if used on unsupported types like int
or float
Ask the user to enter a sentence. Print how many characters it contains:
sentence = input("Enter a sentence: ")
print("Number of characters:", len(sentence))
⬅ Previous Topic
Python iter() Function – Create an Iterator from IterableNext Topic ⮕
Python list() Function – Convert Data to a ListYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.