4 Examples of Python 3 Len function

Table of Contents

The built-in len(obj) function is used to find the lengths of objects by calling their own length methods in python. In this article, we will cover how to use len function to get the length of string, list, tuple, dict.

Python counts the items in a list starting with one, so we shouldn’t run into any off-by-one errors when determining the length.

Finding the length of a String with len function

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

Finding the length of a list with len function

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

Finding the length of a Tuple with len function

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’>

Finding the length of a Dictionary with len function

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

 

Table of Contents

Share on facebook
Facebook
Share on twitter
Twitter
Share on linkedin
LinkedIn

You might also like