Python3 len() Method
Description
Python len() is a Python built-in function that returns the length of an object or the number of elements; it applies to strings, lists, tuples and other data types that have length information.
len() also works with other iterable objects, such as sets.
Syntax
len() method syntax:
len( s )
Parameters
- s -- the object.
Return Value
Returns the length of the object.
Example
The following example shows how to use len():
Length of a string:
Example
text
=
"
Hello, World!
"
length
=
len
(
text
)
(
length
)
Output: 13
In the above example, len(text) returns the number of characters in the string text, including spaces and punctuation; the output is:
13
Length of a list:
Example
my_list
=
[
1
,
2
,
3
,
4
,
5
]
length
=
len
(
my_list
)
(
length
)
Output: 5
In the above example, len(my_list) returns the number of elements in the list my_list; the output is:
5
Length of a tuple:
Example
my_tuple
=
(
10
,
20
,
30
)
length
=
len
(
my_tuple
)
(
length
)
Output: 3
In the above example, len(my_tuple) returns the number of elements in the tuple my_tuple; the output is:
3
Length of a set:
Example
my_set
= {
5
,
10
,
15
,
20
}
length
=
len
(
my_set
)
(
length
)
Output: 4
In the above example, len(my_set) returns the number of unique elements in the set my_set; the output is:
4
Length of a dictionary:
Example
my_dict
= {
"
apple
"
:
3
,
"
banana
"
:
2
,
"
cherry
"
:
4
}
length
=
len
(
my_dict
)
(
length
)
Output: 3
In the above example, len(my_dict) returns the number of key-value pairs in the dictionary my_dict; the output is:
3
In short, the len() function is a very practical tool for determining the length of all kinds of sequences, which is very useful when writing all kinds of Python programs.
** Notes**
- For strings,
len()it returns the number of characters. - For lists and tuples,
len()it returns the number of elements. - For dictionaries,
len()it returns the number of key-value pairs. - For sets,
len()it returns the number of elements in the set.
Python3 Strings