Python3 len() Method
Description
Python len() is a built-in Python function used to return the length of an object or the number of elements. It applies to data types with length information, such as strings, lists, tuples, etc.
len() also works on other iterable objects, such as sets.
Syntax
Syntax of the len() method:
len( s )
Parameters
- s -- An object.
Return Value
Returns the length of the object.
Example
The following examples demonstrate how to use len():
Length of a string:
Example
In the example above, len(text) returns the number of characters in the string text, including spaces and punctuation. The output is:
13
Length of a list:
Example
In the example above, len(my_list) returns the number of elements in the list my_list. The output is:
5
Length of a tuple:
Example
In the example above, len(my_tuple) returns the number of elements in the tuple my_tuple. The output is:
3
Length of a set:
Example
In the example above, len(my_set) returns the number of unique elements in the set my_set. The output is:
4
Length of a dictionary:
Example
In the example above, 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 various types of sequences, which is very useful for writing various 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