Skip to content

Len function in Python

Len function in Python

Len function in Python returns the length (the number of items) of an object . The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

Syntax of len function in Python

len(object)

Parameters of len function in Python

object = It may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set)

Return type of len function in Python

It returns a integer number .

Len function in Python Examples

Example 1: Determine length of a string

# len function with string
x = "rajkumar"
print(len(x))
8
  • In the above code we have used len() function with string
  • As "rajkumar" string has 8 characters so it printed 8 in the output .

Example 2: Determine length of a list

# len function with list
x = ["a","b","c"]
print(len(x))    
3
  • In the above code we have used len() function with list .
  • As the given list x has 3 elements so it printed 3 in the output .

Note :

len() function follows same behavior for tuple and set like list .

Example 3: Determine length of a dictionary

# len function with dictionary
x = {"a":1,"b":2,"c":3,"d":4}
print(len(x))
4
  • In the above code we have used len() function with dictionary .
  • As the given dictionary x has 4 key-value pair so it printed 4 in the output .

Example 4: Determine length of a range datatype

# len function with range datatype
x = range(5)
print(len(x))
5
  • In the above code we have used len function with range datatype .
  • As the given range-object x has 5 numbers(0 to 4) so it printed 5 in the output .

Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .

Leave a Reply