When working with Python iterables, discovering the variety of objects the iterables comprise is a standard operation. Learn to use the built-in Python capabilities len to seek out the size of iterables and rather more.
Python supplies a set of built-in information buildings and a set of strategies for working with them. As well as, there are built-in capabilities that come in useful when working with these information buildings. One such operate is len()
which supplies the variety of objects current in an iterable.
On this tutorial, we’ll learn to use the len()
operate with lists, tuples, strings and extra. We may even see some widespread utilization eventualities.
Let’s get began!👩🏫
Syntax of the Python len() operate
Right here is the syntax to make use of Python’s len operate:
len(iterable)
As seen, the len()
operate required one parameter, viz any legitimate iterable. The iterable is usually a listing, tuple, or string. However it may also be another legitimate sort.
We see that the syntax for the len()
operate is tremendous straightforward. Subsequent, let’s code just a few examples.
📑 For the code examples on this tutorial, you may co-code in a Python REPL.
Utilizing the len() operate with Iterables

With collection
You should utilize the len()
operate to seek out the size of iterables similar to lists, tuples, and strings.
Here is an instance:
>>> nums = [9,3,6,1,2]
>>> len(nums)
5
>>> nums_tup = (9,3,6,1,2)
>>> len(nums_tup)
5
For these information buildings that retailer a string, you usually entry parts utilizing their index or get a section (substring) if wanted.
With different collections
You may also use the len()
operate with different Python collections similar to units and dictionaries.
These information buildings are unordered collections. Though you is probably not excited by ordering the objects, it’s nonetheless helpful to know the whole variety of objects within the assortment.
>>> nums_set = set(nums)
>>> len(nums_set)
5
>>> costs = {'Pocket book':5,'Pencil case':7,'Bookmarks':3,'Pens':1,'Markers':8}
>>> len(costs)
5
Frequent utilization eventualities of the Python len() operate
To this point we now have seen easy examples of utilizing the len()
operate to get the variety of objects in an iterable. Now let’s have a look at the place we are able to use this in follow.
#1. Iteration with For loops
Python for loop supplies a assemble to iterate by iterables within the for merchandise in iterable syntax. However if you wish to entry the index of every merchandise as an alternative of the merchandise itself or each the index and the objects collectively, you need to use the vary()
Operate as proven:
>>> nums = [9,2,4,7,8]
>>> for i in vary(len(nums)):
... print(f"Index {i}: {nums[i]}")
As a result of vary(N)
returns the sequence of integers 0,1,2,…,N – 1, utilizing vary(len(nums))
provides us the set of legitimate indices to loop by.
# Output
Index 0: 9
Index 1: 2
Index 2: 4
Index 3: 7
Index 4: 8
Nevertheless, the really helpful Pythonic option to entry each the index and the factor is to make use of the enumerate operate:
>>> nums = [9,2,4,7,8]
>>> for idx,num in enumerate(nums):
... print(f"Index {idx}: {num}")
# Output
Index 0: 9
Index 1: 2
Index 2: 4
Index 3: 7
Index 4: 8
#2. Conditional looping with Whereas loops
Suppose you have got a listing of numbers nums
. The record methodology pop()
removes the final merchandise within the record and returns it.
So long as the size of the nums
record len(nums)
is larger than zero: there’s a minimum of one factor that may be eliminated.
>>> nums = [9,2,4,7,8]
>>> whereas len(nums) > 0:
... nums.pop()
# Output
8
7
4
2
9
The instance above is a extra specific means of writing the next:
>>> nums = [9,2,4,7,8]
>>> whereas nums:
... nums.pop()
whereas nums:
is equal to the situation “whereas the track record just isn’t empty”.
#3. Verify and validate the size of iterables
One other widespread use of the len operate is to verify and validate the size of sure iterables.
Right here we verify whether or not username
is a sound string based mostly on size (calculated utilizing the len()
operate):
>>> username = "another-random-user"
>>> if len(username) > 10:
... print("Username too lengthy; needs to be 10 characters lengthy at max.")
... elif len(username) < 5:
... print("Username too quick; needs to be a minimum of 5 characters lengthy.")
... else:
... print("Legitimate username!")
Username too lengthy; needs to be 10 characters lengthy at max.
#4. Checklist and dictionary phrases
Ideas in Python present concise syntax to assemble new iterables from present ones. We are able to use built-in capabilities in a comprehension expression.
Checklist comprehension
On this record comprehension we use the len()
operate to get the size of every string within the languages
record.
>>> languages = ['Python','C','Rust','JavaScript']
>>> len_langs = [len(lang) for lang in languages]
>>> len_langs
[6, 1, 4, 10]
Dictionary comprehension
On this dictionary time period we use the languages
record and the len()
operate to assemble a dictionary:
>>> languages = ['Python','C','Rust','JavaScript']
>>> lang_len = {lang:len(lang) for lang in languages}
>>> lang_len
{'Python': 6, 'C': 1, 'Rust': 4, 'JavaScript': 10}
Right here, the keys and values are the language strings and the size of the language strings, respectively.
#5. Key parameter in customized type
Python has the built-in type() methodology to type Python lists into place and the kind() operate to type lists and different iterables.
In each instances you need to use the key
parameter to regulate the kind.
Right here we type the languages
record based mostly on the size of the string.
>>> languages = ['Python','C','Rust','JavaScript']
>>> languages.type(key=len)
>>> languages
['C', 'Rust', 'Python', 'JavaScript']
Within the snippet under, we use the sorted()
operate to acquire a sorted record.
>>> languages = ['Hindi','English','German','French']
>>> sorted(languages,key=len)
['Hindi', 'German', 'French', 'English']
On this instance, each ‘German’ and ‘French’ have 6 characters every. As a result of the sorted()
operate performs a steady type, preserving the order within the authentic record.
#6. Size of NumPy arrays
You may also use the len()
operate with different information buildings similar to NumPy arrays.
>>> import numpy as np
>>> np_array = np.array([3,4,6,9])
>>> sort(np_array)
<class 'numpy.ndarray'>
>>> len(np_array)
4
On this case, np_array
is a vector with 4 parts. So len(np_array)
returns 4, the variety of parts current within the array.
A matrix is a two-dimensional array.
Contemplate the next instance. len(np_array)
is 2, which is the variety of rows.
>>> matrix = [[1,2,3],[4,5,6]]
>>> np_array = np.array(matrix)
>>> np_array
array([[1, 2, 3],
[4, 5, 6]])
>>> len(np_array)
2
To grasp it, let’s return to matrix
. We’ve got a nested record construction which accommodates the outer record two nested lists. And the len()
operate returns the variety of objects in a container (right here they’re two lists):
>>> assist(len)
Assistance on built-in operate len in module builtins:
len(obj, /)
Return the variety of objects in a container.
Nevertheless, if you will work with multidimensional arrays, it is suggested to make use of the form
attribute as an alternative.
>>> np_array.form
(2, 3)
Frequent pitfalls to keep away from when utilizing Python’s len() operate

To wrap up our dialogue, let’s go over some widespread pitfalls to keep away from when utilizing the len operate in Python.
Utilizing Len() with non-iterable information varieties
We all know that the len operate takes solely legitimate iterables as arguments. Because of this in case you name the len operate with an invalid information sort that’s not iterable, you’ll encounter errors.
Such invalid varieties embody the fundamental information varieties similar to integers, floating level numbers, and Booleans:
>>> len(2)
Traceback (most up-to-date name final):
File "<stdin>", line 1, in <module>
TypeError: object of sort 'int' has no len()
>>> len(True)
Traceback (most up-to-date name final):
File "<stdin>", line 1, in <module>
TypeError: object of sort 'bool' has no len()
>>> len(3.14)
Traceback (most up-to-date name final):
File "<stdin>", line 1, in <module>
TypeError: object of sort 'float' has no len()
In Python, mills are memory-efficient decisions to be used instances that require sequence era. The generator object returns the weather of the array – on demand – factor by factor. However generator objects don’t have any size.
So you’ll encounter errors in case you attempt to calculate the size of a generator object:
>>> nums_sq = (i*i for i in vary(10))
>>> nums_sq
<generator object <genexpr> at 0x0157DBC0>
>>> len(nums_sq)
Traceback (most up-to-date name final):
File "<stdin>", line 1, in <module>
TypeError: object of sort 'generator' has no len()
Utilizing len() with tuples of size one
If you happen to solely insert the factor right into a tuple, Python interprets it as a single factor, not a tuple.
Here is an instance:
>>> nums = (1)
>>> len(nums)
Traceback (most up-to-date name final):
File "<stdin>", line 1, in <module>
TypeError: object of sort 'int' has no len()
So when you’ve got a tuple with just one factor, initialize it on this kind: tuple_name = (elt, )
in order that it’s interpreted as a tuple:
>>> nums = (1,)
>>> len(nums)
1
Sum up
Here is a abstract of what we have lined on this tutorial:
- You could find the variety of objects in every iterable utilizing the
len()
operate in Python. The syntax for utilizing the size operate is:len(any-valid-iterable)
. - This consists of strings similar to lists, tuples, and strings. And different collections similar to dictionaries and units.
- The
len()
operate is usually utilized in loops and notions. - You may also use the
len()
act as a very powerful parameter when you might want to alter sorting based mostly on size. For instance, sorting a listing of strings based mostly on their size.
Subsequent, learn to use Python’s sum() operate.