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
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.
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
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.
Become a Member to join the conversation.