Finding length of list in Python


In today’s post, we’ll learn 2 different ways to find the length of a list in Python. The length of a list refers to the number of elements in the list.

We’ll also work on a practice question that requires us to write a function that returns information about the length of a two-dimensional list.

Here are some topics we’ll cover in today’s post:

Key Concepts

Getting the length of a list

To find the length of a list in Python, we can

  • use a built-in function called len(), or
  • use a for loop to iterate through the list and count the elements ourselves.

Using the len() function

Let’s look at the len() function first.

This is a built-in function in Python that accepts an iterable (such as a list, string, tuple or dictionary) as argument and returns the number of elements in the iterable.

Some examples are shown below:

list1 = [2, 1, 4, 1, 6]
list2 = [[2, 4], [6, 7, 1], [10]]

print(len(list1))
print(len(list2))

Here, we declare and initialize two lists – list1 and list2.

list1 contains 5 numbers while list2 contains 3 nested lists.

To get the number of elements in the lists, we pass them to the len() function on lines 4 and 5.

If we run the code above, we’ll get the following output:

5
3

In the first case, we get 5 because list1 contains 5 elements (i.e. 5 numbers).

In the second case, we get 3 because list2 contains 3 elements (i.e. 3 nested lists).

Using a for loop

Next, let’s look at how we can use a for loop to get the length of a list.

To do that, we need to use a for loop to iterate through the list and count the elements ourselves.

An example is shown below:

list1 = [2, 1, 4, 1, 6]

count = 0
for i in list1:
    count += 1

print(count)

Here, we use a for loop (lines 4 and 5) to iterate through list1. With each iteration, we increment count by 1.

After the loop, we use the print() function to print the value of count.

If you run the code above, you’ll get

5

as the output.

The same method works for list with nested lists. If you run the code below:

list2 = [[2, 4], [6, 7, 1], [10]]

count = 0
for i in list2:
    count += 1

print(count)

you’ll get 3 as the output.

Getting the total number of elements of two-dimensional lists

In the previous section, we learned to get the length of a list using the len() function or using a for loop.

If a list contains nested lists (i.e. it is a 2-dimensional list), both methods do not count the number of elements inside the nested lists.

For instance, for list2, both methods give a length of 3. This is because list2 contains 3 elements – [2, 4], [6, 7, 1] and [10].

What happens if we want to get the total number of elements inside the nested lists? To do that, we can

  • use a for loop, or
  • use list comprehension

Let’s see how this works.

Using a for loop

To get the total number of elements in nested lists, we can use the code below:

list2 = [[2, 4], [6, 7, 1], [10]]

count = 0
for i in list2:
    count += len(i)

print(count)

This code is very similar to the code in the previous section. The only difference is on line 5. When we iterate through the elements in list2, instead of simply incrementing count by 1, we increment count by the length of each element in the list.

The first time the loop runs, i equals [2, 4]. Previously, we increment count by 1. Thus, count becomes 1.

Now, we increment count by len(i). In other words, we increment count by 2. Therefore, count becomes 2.

The second time the loop runs, i equals [6, 7, 1] and we increment count by len(i), which equals 3. Therefore, count becomes 5.

Finally, the last time the loop runs, i equals [10] and we increment count by 1. Thus, count becomes 6.

If we run the code above, we’ll get

6

as the output.

Using list comprehension

Besides using a for loop to get the total number of elements in two-dimensional lists, we can use list comprehension.

First, what is list comprehension?

List comprehension is an elegant way to create lists based on existing lists. It allows us to iterate through a list and add elements to a new list based on elements from the existing list. The syntax is as follows:

new_list = [expression for element in original_list]

Let’s look at an example:

numbers = [3, 4, 5]

squares = [x**2 for x in numbers]

print(squares)

Here, we first declare and initialize a list called numbers. Next, we use list comprehension to create a new list called squares, based on the elements in numbers.

When Python sees line 3, it loops through numbers (for x in numbers), evaluates the expression x**2, and appends it to squares.

For instance, the first time the loop runs, x equals 3. Python evaluates the expression x**2 to get 9, and appends 9 to squares.

It keeps doing this until it finishes looping through all the elements in numbers.

If we run the code above, we’ll get

[9, 16, 25]

as the output.

Besides evaluating simple expressions like x**2 to add elements to the new list, list comprehension allows us to add an if condition. We’ve briefly covered this in a previous post.

Let’s go through it again. The syntax for using an if condition in list comprehension is as follows:

new_list = [expression for item in original_list if condition is met]

Let’s look at an example:

a = [12, 4, 6, 2, 15, 17, 18]

b = [x+2 for x in a if x > 10]

print(b)

Here, we want Python to iterate through a (for x in a) and append x+2 to b only if x is greater than 10.

If you run the code above, you’ll get the following output:

[14, 17, 19, 20]

Now, let’s see how we can use list comprehension to get the total number of elements in a list with nested lists.

To do that, we need to use a built-in function called sum(). This function adds the items of an iterable and returns the sum. Let’s look at the code now:

list2 = [[2, 4], [6, 7, 1], [10]]

lenOfNestedLists = [len(x) for x in list2]

print(lenOfNestedLists)
print(sum(lenOfNestedLists))

Here, we use list comprehension to create a new list called lenOfNestedLists. When Python sees line 3, it iterates through list2 (for x in list2), evaluates the expression len(x) and appends it to lenOfNestedLists.

On line 5, we use the print() function to print the value of lenOfNestedLists.

On line 6, we pass lenOfNestedLists to the sum() function to sum up all the elements inside the list.

If we run the code above, we’ll get the following output:

[2, 3, 1]
6

The first line of output gives us the length of each nested list in list2. For instance, the first nested list [2, 4] has a length of 2.

The second line of output sums all the elements in [2, 3, 1]. Hence, we get 6 as the output. This represents the total number of elements in the nested lists in list2.

Practice Question

Great! We are now ready to work on the practice question for today.

Today’s practice question requires us to write a function called shape2D() that accepts a two-dimensional list and returns a tuple containing the number of elements in the list and the length of the largest nested list in it.

For instance, suppose the input list is [[1, 2, 3], [4, 5, 6, 7, 8]], the function should return the tuple (2, 5), where 2 tells us that the input list has two elements and 5 gives us the length of the largest nested list.

Expected Results

To test your function, you can use the statements below:

a = [[2, 4], [6, 7, 1], [10], [1, 2, 3, 5, 6]]

b = [[1, 2, 10], [6]]

c = [[], [], []]

print(shape2D(a))
print(shape2D(b))
print(shape2D(c))

You should get the following output:

(4, 5)
(2, 3)
(3, 0)

Suggested Solution

Click to see suggested solution
def shape2D(myList):
    l = max([len(x) for x in myList])
    b = len(myList)

    return (b, l)

Here, we first define a function called shape2D() that has one parameter – myList.

Inside the function, we use list comprehension ([len(x) for x in myList]) to create a list based on the length of each element in myList.

Next, we pass this list to the max() function to get the length of the largest nested list and assign the result to a variable called l. You can refer to this post for details on the max() function.

After getting the length of the largest nested list, we use the len() function to get the number of elements in myList and assign the result to b.

Finally, we return the values of b and l as a tuple.

With that, the function is complete.

Written by Jamie | Last Updated October 8, 2020

Recent Posts