len Python | Function to get a length of string, array, list, tuple, dictionary, etc

A “len Python” is an inbuilt function and use for getting a number of items (length) in an object. A len() function can get the length of String, list (Array), tuple, dictionary, etc in Python.

Syntax

The syntax of len() is:

Parameters

Object – a sequence (string, bytes, tuple, list, or range) or a collection (dictionary, set or frozen set)

Return Value

The len() function returns an integer value which is the number of elements in an object.

len() Python example

Let’ see the example of How to get the length of the given string, array, list, tuple, dictionary, etc

Characters in a string

Find how many characters are in a strings.

Output: 5

Count byte

Output: Length 6

lists len Python

Example program code of how to get the size of the list(Array) in python using len() function. List indexing starts from 0.

Read more examples:Python length of list

Output: length is 3

tuples len Python

Python Tuples are very similar to Lists, the only difference is that tuples are not mutable. See below example how to get the size of Tuples.

Output: length is 3

range len Python

A Python Range() Function create a sequence of the item at one time. Let’s see example hot find its length.

Output:

The length of the Range is 9

dict len Python

Python dictionary has keys and values. See below code of how to find the length of the dictionary in Python?

Output: The length of the Dictionary is 4

len() works with sets

In a Python set, all elements are unique and must be immutable.

See example of how to get length of set in python.

Output: 3

Q: How len() works for custom objects?

Output: 0
9

Do comment if yo have any doubts and suggestion on this tutorial. It can be you are interview to how find the size or length of given data type.

Note: This example (Project) is developed in PyCharm 2020.1 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.15.4
Python 3.7
All Python Programs code is in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.