Python len() function

Python len() function is very straightforward and easy to use. It is used to find out how many elements there are in different types of data.

If applied on a string it will return the number of characters in it, if applied on a list it will return the number of elements in the list, if applied on a dictionary it will return the number of unique keys in it and so on.

Estimated Time

5 mins

Skill Level

Beginner

Functions

len()

Course Provider

Provided by HolyPython.com

Reasons to Use Python Len Function

There can be many more reasons why you might want to use the len() function.

  • You might want to iterate a function for each item in data, in that case we can know how many items there are. (Usually in Python loops which we will see later)
  • You might want to build a conditional statement based on the size of data (Python conditional statements which we will see later)
  • You might only be interested in words bigger than a specific length (length of strings)
  • You might want to make sure your data is bigger than a certain size (Imagine a Python script that collects data and only writes this collection to a file once a specific length is reached)
  • You might want to make sure your range calculation is correct (len function also works with range object another concept we will see later.)
  • Long story short, there can be many reasons why you might want to use len function to find out the length of strings, lists, tuples, dictionaries and range objects.

Some or all of these situations may occur during any programming task such as operating system operations, scripting, web scraping, data science, working on financial data, digital image manipulation etc.

Function1 : len()

len() is a useful function that can show us the length of different data types.

Example 1: Length of list

>>> lst = [3, 33, 100, 1000, 5]
>>> print(len(lst))

5

Used Where?

len() function is a built-in Python function that works with different types of data. We’ve explained some of the use cases above. Let’s wrap it up once again quickly.

  • it can tell length of a string (number of characters)
  • or it can tell the size of Python collections such as lists and tuples (number of elements)
  • it can also tell the size of a dictionary (number of unique keys)

The reason why you need this information in programming can vary greatly.

  • You might just be curious
  • You might be adding elements to your list or dictionary and want to know the new size (strings and tuples are mutable)
  • You might want to filter certain size of data types.
  • You might use a conditional statement for strings of certain sizes

Syntax do(s)

1) len() is used with an argument inside its parenthesis.

Syntax don't(s)

1) if you fail to specify an argument inside len() function's parenthesis you will get an error.

Example 2: Length of string

>>> my_msg = “Hello World!”
>>> print(len(my_msg))

12

Example 3: Length of tuple

>>> my_tup = (“4k”, “1080p”, “720p”)
>>> print(len(my_tup))

3

Example 4: Length of dictionary

>>> my_dict = {“rainy”: 95, “sunny”: 270}
>>> print(len(my_dict))

2

Example 5: Logical statement with len function

>>> cntry_name = “Papua New Guinea”
>>> mycheck = len(cntry_name) > 5
>>> print(mycheck)

True

1- Here is a nice logic test and the result gets assigned to our variable mycheck as a boolean (in this case True)

Tips

1- Data structures in Python can have other data structures as their elements. For example a list can consist of multiple Python lists inside it. This concept is called nested data in programming and we will have a dedicated Python lesson for Nested Data later.

When you are dealing with nested data you can apply len function to the lists (or tuples or dictionaries) that are nested (inside). Let’s see a simple example. We will elaborate on nested data structures later.

Example 6: Accessing nested data for len function

>>> lst = [[1,2,3], [a,b,c], [True, False, False, True] ]
>>> print(len(lst[0]))
>>> print(len(lst[2]))

3
4

Indexing starts with 0 in Python.

Advanced Concepts (Optional)

1-It may be a bit early for this and possibly confusing but just know the possibilities anyway. len function can also be applied to each element of the list at once using map function (a useful Python function we will explore later). Or it can also be used as an input to create logical statements with filter function (also a Python function we will see Intermediate Lessons).

This goes to show how most basic and little building blocks can be used to create more complex and amazing structures in programming. That’s why it’s important to internalize beginner Python lessons and not rush too much. So, one really questions the long-term effectiveness of some of the approaches in the market such as Learn Python in 1 Hour or Learn Python in 1 Day.

I mean we are all kings and queens but let’s not kid ourselves. This stuff takes some time. Especially if you are a first time programmer or coming from non-CS background there are so many abstract concepts to understand, remember and connect with each other.

So, our advise as HolyPython is take your time, practice, practice, practice and enjoy yourself! It might take a bit longer but it will happen, and it will be worth it. You got this!

Next Lesson: Python .sort() method

“Have you installed Python yet?”
Having Python setup on your computer can expedite the learning experience and help you gain the real life skills in a non-simulation environment. Installing Python can have different nuances that can be confusing for everyone. We compiled a complete tutorial about the best and most convenient Python installing practices Check it out by clicking the button below.
SANDRA FILES