Common Use Cases
In the previous lesson, I showed you how to use the
len() function to find the length of sequences and collections. In this lesson, I’ll show you some common coding patterns where you might use
As you saw previously,
len() finds the length of container-like objects. It is commonly used to determine boundaries within conditionals, loop conditions, and finding mid-points.
00:25 Let’s go back to the REPL and see some of these cases. The first example I’ll show you is when doing boundary checks on the size of an object.
Say you are asking a user to input a username that needs to be between four and ten characters. This function would check that for you. The function uses
len() to determine the length of the input and check the boundary conditions. Similarly, you can use
len() as a loop condition.
Let’s say you wanted to prompt the user for three names. The
while condition here checks the length of the names list and loops until there are three items inside of it. Trying it out.
And there you go, three names completely at random. You can do the same thing but backwards using
pop() to get things out of a list and looping until the list is empty.
Although that works, you won’t see much Python code do it that way. That’s because lists in Python are truthy. That means they return
True if their length is bigger than zero, or
The same thing could be accomplished with less code, and in this case, without the call to
And now some examples to get at different parts of a list, starting with the last part of the list. What if you want the last item?
len() tells you how long something is, and then you can use that as the index in the list.
02:59 Here are some numbers. I’m going to get the fourth item. Remember that lists are zero indexed. And here I can find the index of the last item, subtracting one again because of that zero-indexing thing.
This is such a common use case in Python that it has a shortcut for it, negative indexing. An index of
-1 (minus one) is the last item in the list. Once again, I’ve shown you somewhere where you could use
len(), but it isn’t really needed.
03:41 Let’s try something else. What about the midpoint of the list? For that, you definitely need the length. Here’s numbers again. Calculate the midpoint as the length divided by two.
// (double slash) here indicates integer division. The result will always be an integer. Midway is three. Now using that midway, I can slice the list using the
04:14 That’ll be the first half … and the second half. Because of the integer division, I can do this with an odd number of items as well. Mid is still three, rounded down …
first half hasn’t changed … and the second half has the answer to the universe and everything. Next up, I’ll show you how
len() is used in NumPy and Pandas, two popular third-party libraries.
Become a Member to join the conversation.