Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
In Development Last updated: July 13, 2023
Share on:
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

When working with Python iterables, finding the number of items that the iterables contains is a common operation. Learn how to use Python’s built-in len to find the length of iterables and much more.

Python offers a suite of built-in data structures and a set of methods to work with them. In addition, there are built-in functions that come in handy when working with these data structures. One such function is len() which gives the number of items present in an iterable.

In this tutorial, we’ll learn how to use the len() function with lists, tuples, strings, and more. We’ll also see a few common use cases.

Let’s get started!👩‍🏫

Syntax of the Python len() Function

Here’s the syntax to use Python’s len function:

len(iterable)

As seen, the len() function requires one parameter, which is any valid iterable. The iterable is often one of a list, tuple, or string. But it can also be any other valid type.

We see that the syntax to use the len() function is super simple. Next, let’s proceed to code a few examples.

📑 For the code examples in this tutorial, you can code along in a Python REPL.

Using the len() Function with Iterables

Using-the-len-function-with-Iterables

With Sequences

You can use the len() function to find the length of iterables such as lists, tuples, and strings.

Here’s an example:

>>> nums = [9,3,6,1,2]
>>> len(nums)
5

>>> nums_tup = (9,3,6,1,2)
>>> len(nums_tup)
5

For these data structures that store a sequence, you’ll typically access elements using their index or get a slice (subsequence) as needed.

With Other Collections

You can also use the len() function with other Python collections like sets and dictionaries.

These data structures are unordered collections. While you may not be interested in ordering of the items, it’s still helpful to get the total number of items in the collection.

>>> nums_set = set(nums)
>>> len(nums_set)
5

>>> prices = {'Notebook':5,'Pencil case':7,'Bookmarks':3,'Pens':1,'Markers':8}
>>> len(prices)
5

Common Use Cases of the Python len() Function

So far, we’ve seen simple examples of using the len() function to get the number of items in an iterable. Now let’s see where we may use this in practice.

#1. Iteration Using For Loops

Python for loop provides a construct to loop through iterables in the for an item in iterable syntax. But if you want to access the index of each item instead of the item itself or both the index and the items together, you can use the range() function as shown:

>>> nums = [9,2,4,7,8]
>>> for i in range(len(nums)):
...      print(f"Index {i}: {nums[i]}")

Because range(N) gives the sequence of integers 0,1,2,…,N – 1, using range(len(nums))  gives us the set of valid indices to loop through.

# Output
Index 0: 9
Index 1: 2
Index 2: 4
Index 3: 7
Index 4: 8

However, the recommended Pythonic way to access both index and element is using the enumerate function:

>>> 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 Using While Loops

Say you have a list of numbers nums. The list method pop() removes the last item in the list and returns it.

So long as the length of the nums list len(nums) is greater than zero—there is at least one element that can be removed.

>>> nums = [9,2,4,7,8]
>>> while len(nums) > 0:
...     nums.pop()
# Output
8
7
4
2
9

The above example is a more explicit way of writing the following:

>>> nums = [9,2,4,7,8]
>>> while nums:
...     nums.pop()

while nums: is equivalent to the condition “while the nums list is not empty”.

#3. Checking and Validating the Length of Iterables

Another common use of the len function is in checking and validating the length of certain iterables. 

Here we check if username is a valid string based on the length (computed using the len() function):

>>> username = "another-random-user"
>>> if len(username) > 10:
...     print("Username too long; should be 10 characters long at max.")
... elif len(username) < 5:
...     print("Username too short; should be at least 5 characters long.")
... else:
...     print("Valid username!")
Username too long; should be 10 characters long at max.

#4. List and Dictionary Comprehensions

Comprehensions in Python provide a concise syntax to construct new iterables from existing ones. We can use built-in functions in a comprehension expression.

List Comprehension

In this list comprehension, we use the len() function to get the length of each string in the languages list.

>>> languages = ['Python','C','Rust','JavaScript']
>>> len_langs = [len(lang) for lang in languages]
>>> len_langs
[6, 1, 4, 10]

Dictionary Comprehension

In this dictionary comprehension, we use the languages list and the len() function to construct 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}

Here, the keys and values are the language strings and the length of the language strings, respectively.

#5. Key Parameter in Custom Sorting

Python has the built-in sort() method to sort Python lists in place and the sorted() function to sort lists and other iterables.

In both of these, you can use the key parameter to customize the sorting.

Here, we sort the languages list based on the length of the string.

>>> languages = ['Python','C','Rust','JavaScript']
>>> languages.sort(key=len)
>>> languages
['C', 'Rust', 'Python', 'JavaScript']

In the snippet below, we use the sorted() function to obtain a sorted list.

>>> languages = ['Hindi','English','German','French']
>>> sorted(languages,key=len)
['Hindi', 'German', 'French', 'English']

In this example, both ‘German’ and ‘French’ have 6 characters each. Because the sorted() function performs stable sorting, the ordering in the original list is preserved.

#6. Length of NumPy Arrays

You can also use the len() function with other data structures like NumPy arrays.

>>> import numpy as np
>>> np_array = np.array([3,4,6,9])
>>> type(np_array)
<class 'numpy.ndarray'>
>>> len(np_array)
4

In this case, np_array is a vector with 4 elements. So len(np_array) returns 4, the number of elements present in the array.

A matrix is a two-dimensional array.

Consider the following example. len(np_array) is 2, which is the number 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 understand, let’s go back to matrix. We have a nested list structure where the outer list contains two nested lists. And the len() function returns the number of items in a container (here, it is two lists):

>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

However, as you start working with multidimensional arrays, it’s recommended to use the shape attribute instead.

>>> np_array.shape
(2, 3)

Common Pitfalls To Avoid When Using Python’s len() Function

pitfalls

To wrap up our discussion, let’s go over some of the common pitfalls you should avoid when using the len function in Python.

Using len() with Non-Iterable Data Types

We know that the len function takes in only valid iterables as the argument. Meaning if you call the len function with—an invalid data type—that is not iterable, you’ll run into errors.

Such invalid types include the basic data types such as integers, floating point numbers, and Booleans:

>>> len(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()

>>> len(True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'bool' has no len()

>>> len(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'float' has no len()

In Python, generators are memory-efficient choices for use cases that require sequence generation. The generator object returns the elements of the sequence—on demand—one element at a time. But generator objects do not have a length. 

So you’ll run to errors if you try to compute the length of a generator object:

>>> nums_sq = (i*i for i in range(10))
>>> nums_sq
<generator object <genexpr> at 0x0157DBC0>
>>> len(nums_sq)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'generator' has no len()

Using len() with Tuples of Length One

If you only insert the element in a tuple, Python interprets it as a single element and not as a tuple.

Here’s an example:

>>> nums = (1)
>>> len(nums)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: object of type 'int' has no len()

So when you have a tuple with only one element, initialize it in this form: tuple_name = (elt, ) so that it is interpreted as a tuple:

>>> nums = (1,)
>>> len(nums)
1

Summing Up

Here’s a summary of what we’ve covered in this tutorial:

  • You can find the number of items in any iterable using the len() function in Python. The syntax to use the length function is:  len(any-valid-iterable).
  • This includes sequences such as lists, tuples, and strings. And other collections such as dictionaries and sets.
  • The len() function is commonly used in loops and comprehensions. 
  • You can also use the len() function as the key parameter when you need to customize sorting according to the length. For example: sorting a list of strings based on their length.

Next, learn how to use Python’s sum() function.

  • Bala Priya C
    Author
    Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more…. read more
  • Narendra Mohan Mittal
    Editor

    Narendra Mohan Mittal is a Senior Digital Branding Strategist and Content Editor with over 12 years of versatile experience. He holds an M-Tech (Gold Medalist) and B-Tech (Gold Medalist) in Computer Science & Engineering.


    read more
Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Monday.com is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.
    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder