0
0
Pythonprogramming~5 mins

len() function in Python

Choose your learning style9 modes available
Introduction

The len() function helps you find out how many items are in something, like a list or a word.

When you want to know how many letters are in a word.
When you need to count how many things are in a list or a box.
When checking if a string is empty or has some text.
When you want to loop through all items but need to know how many first.
When you want to limit input size by checking its length.
Syntax
Python
len(some_object)

some_object can be a string, list, tuple, dictionary, or other collections.

The function returns an integer number representing the count of items.

Examples
Counts the number of letters in the word "hello" which is 5.
Python
len("hello")
Counts how many numbers are in the list, which is 4.
Python
len([1, 2, 3, 4])
Counts how many keys are in the dictionary, which is 2.
Python
len({"a": 1, "b": 2})
Sample Program

This program counts the letters in the word "apple" and the number of fruits in the list.

Python
word = "apple"
fruits = ["apple", "banana", "cherry"]
print(len(word))
print(len(fruits))
OutputSuccess
Important Notes

If you use len() on an empty string or list, it returns 0.

Trying len() on a number will cause an error because numbers don't have length.

Summary

len() tells you how many items are inside something.

Works with strings, lists, dictionaries, and more.

Returns a number you can use to make decisions or loops.