📜  len - Python (1)

📅  最后修改于: 2023-12-03 14:43:52.423000             🧑  作者: Mango

len() in Python

The len() function is a built-in function in Python that returns the length of an object, such as a string or a list. It takes one argument, which is the object whose length needs to be determined.

Syntax
len(object)

Parameters:

  • object: The object whose length needs to be determined.

Return Value:

  • The length of the object as an integer.
Example Usage
# Length of a string
fruit = "apple"
print(len(fruit))  # Output: 5

# Length of a list
numbers = [1, 2, 3, 4, 5]
print(len(numbers))  # Output: 5

# Length of a tuple
name = ("John", "Doe")
print(len(name))  # Output: 2
Special Cases

The len() function behaves differently for various data types.

  • For strings, len() returns the number of characters in the string.
  • For lists and tuples, len() returns the number of items in the sequence.
  • For dictionaries, len() returns the number of key-value pairs.
  • For sets and frozensets, len() returns the number of elements.
  • For other iterable objects, len() returns the number of items returned by the __len__() method.
Conclusion

The len() function is an important tool for working with sequences and other objects in Python. It is a simple way to determine the length of an object, which can be helpful when writing programs that need to work with different types of data.