In this article we’ll go through the Python len function and it’s uses, complete with several examples.

As the name suggests, the Python len Function is used to calculate the length of an sequence or iteratable. The len function will count the number of elements within the sequence or iteratable.

### Syntax

A `len()` function takes only one input as parameter.

``len(sequence)``

#### Example Set 1

Remember, a string also counts as an iteratable, where each character is a string of length one. In dictionaries, the number of key value pairs are counted.

```>>> len("String")
6

>>> X = [4,5,6,6]
>>> len(X)
4

>>> X = {1 : "Apples", 2 : "Bananas", 3 : "Cucumbers"}
>>> len(X)
3

>>> X = { 3, 4, 1, 7, 9 }
>>> len(X)
5

>>> X = ( 2, 3, 1, 6, 7 )
>>> len(X)
5
```

#### Example Set 2

You can also use `len()` on the `range()` function or Numpy’s `arange()` function. In this example set, you’ll also find Numpy’s Arrays.

While finding the length of a one dimensional Array is easy enough, a 2-Dimensional Array is trickier. It’s best to think of it in rows and columns. Simply inserting the Array into the `len()` will only return the number of rows in it. However, if you want to find the second dimension, you can simply find the length of one the rows. Hence, we do `X`. It doesn’t matter which row, it can be the first, the second or the third.

```>>> X = range(100)
>>> len(X)
100

>>> import numpy
>>> X = numpy.arange(10)
>>> len(X)
10

>>> X = numpy.zeros(5)
>>> len(X)
5

>>> X = numpy.zeros((3,4))
>>> len(X)
3
>>> len(X)
4
```

This marks the end of the Python len Function. Any suggestions or contributions for CodersLegacy are more than welcome. Questions can be asked in the comment section below.

Here’s a link back to the main Python Built-in Functions page.

Subscribe
Notify of 