Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python3 len() Method

Python3 len() Method

Python3 Strings Python3 Strings


Description

Python len() is a Python built-in function that returns the length of an object or the number of elements; it applies to strings, lists, tuples and other data types that have length information.

len() also works with other iterable objects, such as sets.

Syntax

len() method syntax:


len( s )

Parameters

Return Value

Returns the length of the object.

Example

The following example shows how to use len():

Length of a string:

Example

text

=

"

Hello, World!

"

length

=

len

(

text

)

print

(

length

)

Output: 13

In the above example, 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 above example, 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 above example, 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 above example, 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 above example, 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 all kinds of sequences, which is very useful when writing all kinds of Python programs.


** Notes**

Python3 Strings Python3 Strings