Python len() function


len() Function in Python

The len() function in Python is used to determine the length (i.e., the number of characters) of a string. It can also be used with other data types like lists, tuples, dictionaries, and more, but when applied to strings, it counts the total number of characters in the string.

Syntax:

len(string)
  • string: The string whose length you want to find.

Example:

# Example 1: Finding the length of a string my_string = "Hello, Python!" length = len(my_string) print(length) # Output: 13

In the example above:

  • The string "Hello, Python!" has 13 characters, including spaces and punctuation.
  • The len() function returns 13 because it counts every character.

Example with an empty string:

# Example 2: Length of an empty string empty_string = "" print(len(empty_string)) # Output: 0

Here, the string is empty, so len() returns 0.

Example with spaces:

# Example 3: String with spaces string_with_spaces = " " print(len(string_with_spaces)) # Output: 3

In this example, there are three spaces in the string, and len() counts each space, returning 3.

Key Points:

  • Whitespace characters like spaces, tabs, and newlines are also counted by the len() function.
  • The function works with any iterable (not just strings), such as lists, tuples, and dictionaries.