Movatterモバイル変換


[0]ホーム

URL:


— FREE Email Series —

🐍 Python Tricks 💌

Python Tricks Dictionary Merge

🔒 No spam. Unsubscribe any time.

Browse TopicsGuided Learning Paths
Basics Intermediate Advanced
aialgorithmsapibest-practicescareercommunitydatabasesdata-sciencedata-structuresdata-vizdevopsdjangodockereditorsflaskfront-endgamedevguimachine-learningnewsnumpyprojectspythonstdlibtestingtoolsweb-devweb-scraping

Table of Contents

Recommended Course

Using the len() Function in Python

Python's len() Function

24m · 6 lessons

Using the len() Function in Python

Using the len() Function in Python

byStephen GruppettaReading time estimate 25mbasicspython

Table of Contents

Remove ads

Recommended Course

Python's len() Function(24m)

Thelen() function in Python is a powerful and efficient tool used to determine the number of items in objects, such as sequences or collections. You can uselen() with various data types, including strings, lists, dictionaries, and third-party types like NumPy arrays and pandas DataFrames. Understanding howlen() works with different data types helps you write more efficient and concise Python code.

Usinglen() in Python is straightforward for built-in types, but you can extend it to your custom classes by implementing the.__len__() method. This allows you to customize whatlength means for your objects. For example, with pandas DataFrames,len() returns the number of rows. Masteringlen() not only enhances your grasp of Python’s data structures but also empowers you to craft more robust and adaptable programs.

By the end of this tutorial, you’ll understand that:

  • Thelen() function in Python returns the number of items in an object, such as strings, lists, or dictionaries.
  • To get the length of a string in Python, you uselen() with the string as an argument, likelen("example").
  • To find the length of a list in Python, you pass the list tolen(), likelen([1, 2, 3]).
  • Thelen() function operates in constant time,O(1), as it accesses a length attribute in most cases.

In this tutorial, you’ll learn when to use thelen() Python function and how to use it effectively. You’ll discover which built-in data types are valid arguments forlen() and which ones you can’t use. You’ll also learn how to uselen() with third-party types likendarray inNumPy andDataFrame inpandas, and with your own classes.

Free Bonus:Click here to get a Python Cheat Sheet and learn the basics of Python 3, like working with data types, dictionaries, lists, and Python functions.

Getting Started With Python’slen()

The functionlen() is one of Python’s built-infunctions. It returns the length of an object. For example, it can return the number of items in a list. You can use the function with many different data types. However, not all data types are valid arguments forlen().

You can start by looking at the help for this function:

Python
>>>help(len)Help on built-in function len in module builtins:len(obj, /)    Return the number of items in a container.

The function takes an object as an argument and returns the length of that object. Thedocumentation forlen() goes a bit further:

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set). (Source)

When you use built-in data types and many third-party types withlen(), the function doesn’t need to iterate through the data structure. The length of a container object is stored as an attribute of the object. The value of this attribute is modified each time items are added to or removed from the data structure, andlen() returns the value of the length attribute. This ensures thatlen() works efficiently.

In the following sections, you’ll learn about how to uselen() with sequences and collections. You’ll also learn about some data types that you cannot use as arguments for thelen() Python function.

Usinglen() With Built-in Sequences

Asequence is a container with ordered items.Lists, tuples, andstrings are three of the basic built-in sequences in Python. You can find the length of a sequence by callinglen():

Python
>>>greeting="Good Day!">>>len(greeting)9>>>office_days=["Tuesday","Thursday","Friday"]>>>len(office_days)3>>>london_coordinates=(51.50722,-0.1275)>>>len(london_coordinates)2

When finding the length of the stringgreeting, the listoffice_days, and the tuplelondon_coordinates, you uselen() in the same manner. All three data types are valid arguments forlen().

The functionlen() always returns an integer as it’s counting the number of items in the object that you pass to it. The function returns0 if the argument is an empty sequence:

Python
>>>len("")0>>>len([])0>>>len(())0

In the examples above, you find the length of an empty string, an empty list, and an empty tuple. The function returns0 in each case.

Arange object is also a sequence that you can create usingrange(). Arange object doesn’t store all the values but generates them when they’re needed. However, you can still find the length of arange object usinglen():

Python
>>>len(range(1,20,2))10

This range of numbers includes the integers from1 to19 with increments of2. The length of arange object can be determined from the start, stop, and step values.

In this section, you’ve used thelen() Python function with strings, lists, tuples, andrange objects. However, you can also use the function with any other built-in sequence.

Usinglen() With Built-in Collections

At some point, you may need to find the number of unique items in a list or another sequence. You can usesets andlen() to achieve this:

Python
>>>importrandom>>>numbers=[random.randint(1,20)for_inrange(20)]>>>numbers[3, 8, 19, 1, 17, 14, 6, 19, 14, 7, 6, 1, 17, 10, 8, 14, 17, 10, 2, 5]>>>unique_numbers=set(numbers)>>>unique_numbers{1, 2, 3, 5, 6, 7, 8, 10, 14, 17, 19}>>>len(unique_numbers)11

You generate the listnumbers using alist comprehension, and it contains twenty random numbers ranging between1 and20. The output will be different each time the code runs since you’re generating random numbers. In this particular run, there are eleven unique numbers in the list of twenty randomly generated numbers.

Another built-in data type that you’ll use often is thedictionary. In a dictionary, each item consists of a key-value pair. When you use a dictionary as an argument forlen(), the function returns the number of items in the dictionary:

Python
>>>len({"James":10,"Mary":12,"Robert":11})3>>>len({})0

The output from the first example shows that there are three key-value pairs in this dictionary. As was the case with sequences,len() will return0 when the argument is either an empty dictionary or an empty set. This leads to empty dictionaries and empty sets being falsy.

Exploringlen() With Other Built-in Data Types

You can’t use all built-in data types as arguments forlen(). For data types that don’t store more than one item within them, the concept of length isn’t relevant. This is the case with numbers and Boolean types:

Python
>>>len(5)Traceback (most recent call last):...TypeError:object of type 'int' has no len()>>>len(5.5)Traceback (most recent call last):...TypeError:object of type 'float' has no len()>>>len(True)Traceback (most recent call last):...TypeError:object of type 'bool' has no len()>>>len(5+2j)Traceback (most recent call last):...TypeError:object of type 'complex' has no len()

Theinteger, float,Boolean, andcomplex types are examples of built-in data types that you can’t use withlen(). The function raises aTypeError when the argument is an object of a data type that doesn’t have a length.

You can also explore whether it’s possible to use iterators and generators as arguments forlen():

Python
>>>importrandom>>>numbers=[random.randint(1,20)for_inrange(20)]>>>len(numbers)20>>>numbers_iterator=iter(numbers)>>>len(numbers_iterator)Traceback (most recent call last):...TypeError:object of type 'list_iterator' has no len()>>>numbers_generator=(random.randint(1,20)for_inrange(20))>>>len(numbers_generator)Traceback (most recent call last):...TypeError:object of type 'generator' has no len()

You’ve already seen that a list has a length, meaning you can use it as an argument inlen(). You create an iterator from the list using the built-in functioniter(). In an iterator, each item is fetched whenever it’s required, such as when the functionnext() is used or in a loop. However, you can’t use an iterator inlen().

You get aTypeError when you try to use an iterator as an argument forlen(). As the iterator fetches each item as and when it’s needed, the only way to measure its length is to exhaust the iterator. An iterator can also be infinite, such as the iterator returned byitertools.cycle(), and therefore its length can’t be defined.

You can’t usegenerators withlen() for the same reason. The length of these objects can’t be measured without using them up.

Exploringlen() Further With Some Examples

In this section, you’ll learn about some common use cases forlen(). These examples will help you understand better when to use this function and how to use it effectively. In some of the examples, you’ll also see cases wherelen() is a possible solution but there may be more Pythonic ways of achieving the same output.

Verifying the Length of a User Input

A common use case oflen() is to verify the length of a sequence input by a user:

Pythonusername.py
username=input("Choose a username: [4-10 characters] ")if4<=len(username)<=10:print(f"Thank you. The username{username} is valid")else:print("The username must be between 4 and 10 characters long")

In this example, you use anif statement to check if the integer returned bylen() is greater than or equal to4 and less than or equal to10. You can run this script and you’ll get an output similar to the one below:

Shell
$pythonusername.pyChoose a username: [4-10 characters] stephen_gThank you. The username stephen_g is valid

The username is nine characters long in this case, so the condition in theif statement evaluates toTrue. You can run the script again and input an invalid username:

Shell
$pythonusername.pyChoose a username: [4-10 characters] sgThe username must be between 4 and 10 characters long

In this case,len(username) returns2, and the condition in theif statement evaluates toFalse.

Ending a Loop Based on the Length of an Object

You’ll uselen() if you need to check when the length of a mutable sequence, such as a list, reaches a specific number. In the following example, you ask the user to enter three username options, which you store in a list:

Pythonusername.py
usernames=[]print("Enter three options for your username")whilelen(usernames)<3:username=input("Choose a username: [4-10 characters] ")if4<=len(username)<=10:print(f"Thank you. The username{username} is valid")usernames.append(username)else:print("The username must be between 4 and 10 characters long")print(usernames)

You’re now using the result fromlen() in thewhile statement. If the user enters an invalid username, you don’t keep the input. When the user enters a valid string, you append it to the listusernames. The loop repeats until there are three items in the list.

You could even uselen() to check when a sequence is empty:

Python
>>>colors=["red","green","blue","yellow","pink"]>>>whilelen(colors)>0:...print(f"The next color is{colors.pop(0)}")...The next color is redThe next color is greenThe next color is blueThe next color is yellowThe next color is pink

You use the list method.pop() to remove the first item from the list in each iteration until the list is empty. If you’re using this method on large lists, you should remove items from the end of the list as this is more efficient. You can also use thedeque data type from thecollections built-in module, which allows you to pop from the left efficiently.

There’s a more Pythonic way of achieving the same output by using thetruthiness of sequences:

Python
>>>colors=["red","green","blue","yellow","pink"]>>>whilecolors:...print(f"The next color is{colors.pop(0)}")...The next color is redThe next color is greenThe next color is blueThe next color is yellowThe next color is pink

An empty list is falsy. This means that thewhile statement interprets an empty list asFalse. A non-empty list is truthy, and thewhile statement treats it asTrue. The value returned bylen() determines the truthiness of a sequence. A sequence is truthy whenlen() returns any non-zero integer and falsy whenlen() returns0.

Finding the Index of the Last Item of a Sequence

Imagine you want to generate a sequence of random numbers in the range1 to10 and you’d like to keep adding numbers to the sequence until the sum of all the numbers exceeds21. The following code creates an empty list and uses awhile loop to populate the list:

Python
>>>importrandom>>>numbers=[]>>>whilesum(numbers)<=21:...numbers.append(random.randint(1,10))...>>>numbers[3, 10, 4, 7]>>>numbers[len(numbers)-1]7>>>numbers[-1]# A more Pythonic way to retrieve the last item7>>>numbers.pop(len(numbers)-1)# You can use numbers.pop(-1) or numbers.pop()7>>>numbers[3, 10, 4]

You append random numbers to the list until the sum exceeds21. The output you’ll get will vary as you’re generating random numbers. To display the last number in the list, you uselen(numbers) and subtract1 from it since the first index of the list is0. Indexing in Python allows you to use the index-1 to obtain the last item in a list. Therefore, although you can uselen() in this case, you don’t need to.

You want to remove the last number in the list so that the sum of all numbers in the list doesn’t exceed21. You uselen() again to work out the index of the last item in the list, which you use as an argument for the list method.pop(). Even in this instance, you could use-1 as an argument for.pop() to remove the last item from the list and return it. As a final option, you could leave out the argument altogether as the default is to pop the last element.

Splitting a List Into Two Halves

If you need to split a sequence into two halves, you’ll need to use the index that represents the midpoint of the sequence. You can uselen() to find this value. In the following example, you’ll create a list of random numbers and then split it into two smaller lists:

Python
>>>importrandom>>>numbers=[random.randint(1,10)for_inrange(10)]>>>numbers[9, 1, 1, 2, 8, 10, 8, 6, 8, 5]>>>first_half=numbers[:len(numbers)//2]>>>second_half=numbers[len(numbers)//2:]>>>first_half[9, 1, 1, 2, 8]>>>second_half[10, 8, 6, 8, 5]

In the assignment statement where you definefirst_half, you use the slice that represents the items from the beginning ofnumbers up to the midpoint. You can work out what the slice represents by breaking down the steps you use in the slice expression:

  1. First,len(numbers) returns the integer10.
  2. Next,10 // 2 returns the integer5 as you use theinteger division operator.
  3. Finally,0:5 is a slice that represents the first five items, which have indices0,1,2,3, and4. Note that the endpoint is excluded.

In the next assignment, where you definesecond_half, you use the same expression in the slice. However, in this case, the integer5 represents the start of the range. The slice is now5: to represent the items from index5 up to the end of the list.

If your original list contains an odd number of items, then half of its length will no longer be a whole number. When you use integer division, you obtain thefloor of the number. The listfirst_half will now contain one less item thansecond_half.

You can try this out by creating an initial list of eleven numbers instead of ten. The resulting lists will no longer be halves, but they’ll represent the closest alternative to splitting an odd sequence.

Using thelen() Function With Third-Party Libraries

You can also use Python’slen() with several custom data types from third-party libraries. In the last section of this tutorial, you’ll learn how the behavior oflen() depends on the class definition. In this section, you’ll look at examples of usinglen() with data types from two popular third-party libraries.

NumPy’sndarray

TheNumPy module is the cornerstone of all quantitative applications of programming in Python. The module introduces thenumpy.ndarray data type. This data type, along with functions within NumPy, is ideally suited for numerical computations and is the building block for data types in other modules.

Before you can start using NumPy, you’ll need to install the library. You can use Python’s standard package manager,pip, and run the following command in the console:

Shell
$python-mpipinstallnumpy

You’ve installed NumPy, and now you can create a NumPy array from a list and uselen() on the array:

Python
>>>importnumpyasnp>>>numbers=np.array([4,7,9,23,10,6])>>>type(numbers)<class 'numpy.ndarray'>>>>len(numbers)6

The NumPy functionnp.array() creates an object of typenumpy.ndarray from the list you pass as an argument.

However, NumPy arrays can have more than one dimension. You can create a two-dimensional array by converting a list of lists into an array:

Python
>>>importnumpyasnp>>>numbers=[    [11, 1, 10, 10, 15],    [14, 9, 16, 4, 4],    [28, 1, 19, 7, 7],]>>>numbers_array=np.array(numbers)>>>numbers_arrayarray([[11,  1, 10, 10, 15],       [14,  9, 16,  4,  4],       [28,  1, 19,  7,  7])>>>len(numbers_array)3>>>numbers_array.shape(3, 5)>>>len(numbers_array.shape)2>>>numbers_array.ndim2

The listnumbers consists of three lists, each containing five integers. When you use this list of lists to create a NumPy array, the result is an array with three rows and five columns. The function returns the number of rows in the array when you pass this two-dimensional array as an argument inlen().

To get the size of both dimensions, you use the property.shape, which is a tuple showing the number of rows and columns. You obtain the number of dimensions of a NumPy array either by using.shape andlen() or by using the property.ndim.

In general, when you have an array with any number of dimensions,len() returns the size of the first dimension:

Python
>>>importnumpyasnp>>>array_3d=np.random.randint(1,20,[2,3,4])>>>array_3darray([[[14,  9, 15, 14],        [17, 11, 10,  5],        [18,  1,  3, 12]],       [[ 1,  5,  6, 10],        [ 6,  3,  1, 12],        [ 1,  4,  4, 17]]])>>>array_3d.shape(2, 3, 4)>>>len(array_3d)2

In this example, you create a three-dimensional array with the shape(2, 3, 4) where each element is a random integer between1 and20. You use the functionnp.random.randint() to create an array this time. The functionlen() returns2, which is the size of the first dimension.

Check outNumPy Tutorial: Your First Steps Into Data Science in Python to learn more about using NumPy arrays.

Pandas’DataFrame

TheDataFrame type in thepandas library is another data type that is used extensively in many applications.

Before you can use pandas, you’ll need to install it by using the following command in the console:

Shell
$python-mpipinstallpandas

You’ve installed the pandas package, and now you can create a DataFrame from a dictionary:

Python
>>>importpandasaspd>>>marks={    "Robert": [60, 75, 90],    "Mary": [78, 55, 87],    "Kate": [47, 96, 85],    "John": [68, 88, 69],}>>>marks_df=pd.DataFrame(marks,index=["Physics","Math","English"])>>>marks_df         Robert  Mary  Kate  JohnPhysics      60    78    47    68Math         75    55    96    88English      90    87    85    69>>>len(marks_df)3>>>marks_df.shape(3, 4)

The dictionary’s keys are strings representing the names of students in a class. The value of each key is a list with the marks for three subjects. When you create a DataFrame from this dictionary, you define the index using a list containing the subject names.

The DataFrame has three rows and four columns. The functionlen() returns the number of rows in the DataFrame. TheDataFrame type also has a.shape property, which you can use to show that the first dimension of a DataFrame represents the number of rows.

You’ve seen howlen() works with a number of built-in data types and also with some data types from third-party modules. In the following section, you’ll learn how to define any class so that it’s usable as an argument for thelen() Python function.

You can explore the pandas module further inThe Pandas DataFrame: Make Working With Data Delightful.

Usinglen() on User-Defined Classes

When you define a class, one of the special methods you can define is.__len__(). Thesespecial methods are called dunder methods as they havedouble underscores at the beginning and end of the method names. Python’s built-inlen() function calls its argument’s.__len__() method.

In the previous section, you’ve seen howlen() behaves when the argument is a pandasDataFrame object. This behavior is determined by the.__len__() method for theDataFrame class, which you can see in the module’ssource code inpandas.core.frame:

Python
classDataFrame(NDFrame,OpsMixin):# ...def__len__(self)->int:"""        Returns length of info axis, but here we use the index.        """returnlen(self.index)

This method returns the length of the DataFrame’s.index property usinglen(). This dunder method defines the length of a DataFrame to be equal to the number of rows in the DataFrame as represented by.index.

You can explore the.__len__() dunder method further with the following toy example. You’ll define a class namedYString. This data type is based on the built-in string class, but objects of typeYString give the letter Y more importance than all the other letters:

Pythonystring.py
classYString(str):def__init__(self,text):super().__init__()def__str__(self):"""Display string as lowercase except for Ys that are uppercase"""returnself.lower().replace("y","Y")def__len__(self):"""Returns the number of Ys in the string"""returnself.lower().count("y")

The.__init__() method ofYString initializes the object using the.__init__() method of the parentstr class. You achieve this using the functionsuper(). The.__str__() method defines the way the object is displayed. The functionsstr(),print(), andformat() all call this method. For this class, you represent the object as an all-lowercase string with the exception of the letter Y, which you display as uppercase.

For this toy class, you define the object’s length as the number of occurrences of the letter Y in the string. Therefore, the.__len__() method returns the count of the letter Y.

You can create an object of classYString and find its length. The module name used for the example above isystring.py:

Python
>>>fromystringimportYString>>>message=YString("Real Python? Yes! Start reading today to learn Python")>>>print(message)real pYthon? Yes! start reading todaY to learn pYthon>>>len(message)# Returns number of Ys in message4

You create an object of typeYString from a string and show the representation of the object usingprint(). You then use the objectmessage as an argument forlen(). This calls the class’s.__len__() method, and the result is the number of occurrences of the letter Y inmessage. In this case, the letter Y appears four times.

TheYString class is not a very useful one, but it helps illustrate how you can customize the behavior oflen() to suit your needs. The.__len__() method must return a non-negative integer. Otherwise, it raises an error.

Another special method is the.__bool__() method, which determines how an object can be converted to a Boolean. The.__bool__() dunder method is not normally defined for sequences and collections. In these cases, the.__len__() method determines the truthiness of an object:

Python
>>>fromystringimportYString>>>first_test="tomorrow">>>second_test="today">>>bool(first_test)True>>>bool(YString(first_test))False>>>bool(second_test)True>>>bool(YString(second_test))True

The variablefirst_string doesn’t have a Y in it. As shown by the output frombool(), the string is truthy as it’s non-empty. However, when you create an object of typeYString from this string, the new object is falsy as there are no Y letters in the string. Therefore,len() returns0. In contrast, the variablesecond_string does include the letter Y, and so both the string and the object of typeYString are truthy.

You can read more about using object-oriented programming and defining classes inObject-Oriented Programming (OOP) in Python.

Conclusion

You’ve explored how to uselen() to determine the number of items in sequences, collections, and other data types that hold several items at a time, such as NumPy arrays and pandas DataFrames.

Thelen() Python function is a key tool in many programs. Some of its uses are straightforward, but there’s a lot more to this function than its most basic use cases, as you’ve seen in this tutorial. Knowing when you can use this function and how to use it effectively will help you write neater code.

In this tutorial, you’ve learned how to:

  • Find the length ofbuilt-in data types usinglen()
  • Uselen() withthird-party data types
  • Provide support forlen() withuser-defined classes

You now have a good foundation for understanding thelen() function. Learning more aboutlen() helps you understand the differences between data types better. You’re ready to uselen() in your algorithms and to improve the functionality of some of your class definitions by enhancing them with the.__len__() method.

Frequently Asked Questions

Now that you have some experience with thelen() function in Python, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs sum up the most important concepts you’ve covered in this tutorial. Click theShow/Hide toggle beside each question to reveal the answer.

Thelen() function in Python is a built-in function that returns the length of an object. It provides the number of items in a container, including sequences like strings, lists, and tuples or collections like dictionaries and sets. The function is efficient because it typically retrieves the length from an attribute stored within the object.

You can uselen() with several built-in data types, including strings, lists, tuples, dictionaries, sets, and range objects. Additionally,len() can be used with third-party data types like NumPy arrays and pandas DataFrames. For user-defined classes, you can implement the.__len__() method to define howlen() should behave.

len() raises aTypeError for data types that don’t inherently have a length, such as integers, floats, Booleans, and complex numbers. These types don’t contain multiple items, so the concept of length doesn’t apply to them.

Thelen() function is generally very efficient because it often returns a precomputed length stored as an attribute of the object. This means thatlen() can retrieve the length without having to iterate through the entire data structure, making it a constant-time operation,O(1), for most data types.

Yes, you can customize the behavior oflen() for your own classes by defining the.__len__() special method. This method should return a non-negative integer representing the length of your custom object. By implementing.__len__(), you allow instances of your class to be used as arguments for thelen() function.

Recommended Course

Python's len() Function(24m)

🐍 Python Tricks 💌

Get a short & sweetPython Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Python Tricks Dictionary Merge

AboutStephen Gruppetta

Stephen obtained a PhD in physics and worked as a physicist in academia for over a decade before becoming a Python educator. He's constantly looking for simple ways to explain complex things in Python.

» More about Stephen

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

MasterReal-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

MasterReal-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students.Get tips for asking good questions andget answers to common questions in our support portal.


Looking for a real-time conversation? Visit theReal Python Community Chat or join the next“Office Hours” Live Q&A Session. Happy Pythoning!

Keep Learning

Related Topics:basicspython

Related Learning Paths:

Related Courses:

Related Tutorials:

Keep reading Real Python by creating a free account or signing in:

Already have an account?Sign-In

Almost there! Complete this form and click the button below to gain instant access:

Python Logo

Get the Python Cheat Sheet (Free PDF)

🔒 No spam. We take your privacy seriously.


[8]ページ先頭

©2009-2026 Movatter.jp