Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Python's len() Function (Overview)

In many situations, you’ll need to find the number of items stored in a data structure. Python’s built-in function len() is the tool that will help you with this task.

There are some cases in which the use of len() is straightforward. However, there are other times when you’ll need to understand how this function works in more detail and how to apply it to different data types.

In this course, you’ll learn how to:

  • Find the length of built-in data types using len()
  • Use len() with third-party data types
  • Provide support for len() with user-defined classes

Sample Code (.zip)

5.8 KB

Course Slides (.pdf)

975.0 KB

00:00 Welcome to Using the len() Function in Python. My name is Christopher, and I will be your guide.

00:07 This course is all about Python’s built-in len() function that is used to find the lengths of container-like objects. I’ll be covering how to find the length of a sequence or collection, using len() with third-party libraries like NumPy and Pandas, and writing your own classes that can be used with len().

00:27 The code in this course was tested with Python 3.10. The len() function has been around since almost the beginning, so if you’re on anything Python 3, you should be good. For most of the code, even 2.7 will work.

00:40 len() is one of the many built-in functions that come as part of the Python standard library. It is used to find the length of things, typically objects that act like containers for other objects.

00:51 len() works on most of the built-in data types and not surprisingly helps you find the length of strings, lists, tuples, and dictionaries, amongst other things.

01:01 Everything in Python is an object, and operators are built through special methods on these objects. The len() function uses just such a special function called __len__().

01:11 Dunder is what the cool kids call those double underscores (__), or at least I’m assuming they were cool. When I was listening in, they wouldn’t let me join their conversation.

01:20 Any object that implements __len__() can support the len() function. This means you can write your own, and many third-party libraries that have container-like objects do just that. This course will show you two examples, NumPy and Pandas.

01:37 Next up, let’s dive into len(). I’ll show you a quick overview and then use the REPL to show you what it is all about.

Become a Member to join the conversation.