howtouselinux

Understanding Python len function

Table of Contents

The len() function is a built-in function in Python that returns the length of a given object. The object can be a list, string, tuple or dict. The function returns an integer value which is the length of the object.

Use Len function to find the length of a String in Python

A string in Python is a sequence of characters. It is a derived data type. Strings are immutable. This means that once defined, they cannot be changed.We can pass the len() function a string value (or a variable containing a string), and the function evaluates to the integer value of the number of characters in that string.

>>> len(‘hello’)
5
>>> len(‘My very energetic monster just scarfed nachos.’)
46
>>> len(”)
0

Use len function to find the length of a list in Python

A list is a collection of items in a particular order. We can make a list that includes the letters of the alphabet, the digits from 0–9, or the names of all the people in our family. We can put anything we want into a list, and the items in our list don’t have to be related in any particular way. Because a list usually contains more than one element, it’s a good idea to make the name of our list plural, such as letters, digits, or names.

The len() function can return the number of elements or values in the list, as shown in the following example:

>>> avengers = [‘hulk’, ‘iron-man’, ‘Captain-America’, ‘Thor’]
>>> len(avengers)
4

Use Len function to get the length of a Tuple in Python

A tuple is a container that stores a collection of items, like in a list. The major difference between a tuple and a list is that the element in a tuple cannot be changed. They are immutable. We can also find the number of elements in a tuple by using the len() function.

>>> names = (‘Mike’, ‘Josh’, ‘Ope’, ‘Toby’, ‘Fred’, ‘Krish’)
>>> print(len(names))
6
>>> type(names)
<type ‘tuple’>

Use Len function to get the length of a Dictionary in Python

A dictionary is similar to a list, but the order of items doesn’t matter, and they aren’t selected by an offset such as 0 or 1.
Instead, we specify a unique key to associate with each value. This key is often a string, but it can actually be any of Python’s immutable types: boolean, integer, float, tuple, string, and others. Dictionaries are mutable, so we can add, delete, and change their key-value elements.

>>> bierce = {
… “day”: “A period of twenty-four hours, mostly misspent”,
… “positive”: “Mistaken at the top of one’s voice”,
… “misfortune”: “The kind of fortune that never misses”,
… }
>>> type(bierce)
<type ‘dict’>
>>> print(len(bierce))
3

 

David Cao
David Cao

Hey there! I am David, a Cloud & DevOps Enthusiast and 18 years of experience as a Linux engineer. I work with AWS, Git & GitHub, Linux, Python, Ansible, and Bash. I am a technical blogger and a Software Engineer, enjoy sharing my learning and contributing to open-source.