Python3 len() Method

Python3 字符串Python3 Strings


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

text = "Hello, World!" length = len(text) print(length) # Output: 13

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

my_list = [1, 2, 3, 4, 5] length = len(my_list) print(length) # Output: 5

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

my_tuple = (10, 20, 30) length = len(my_tuple) print(length) # Output: 3

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

my_set = {5, 10, 15, 20} length = len(my_set) print(length) # Output: 4

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

my_dict = {"apple": 3, "banana": 2, "cherry": 4} length = len(my_dict) print(length) # Output: 3

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 字符串Python3 Strings

Other Extensions