Last Updated on February 17, 2020 by Brad Cypert
When writing Python, it’s fairly common to find yourself working with lists of data. Usually, you’ll also find yourself trying to figure out just how my items are in that list. Thankfully, in Python, finding the length of a list is fairly easy.
my_list = [1,2,3,4,5] print("The length of this list is:", len(my_list))
The key takeaway here is the
len function that’s built into Python. No external library required! The
len function takes in a sequence or a collection and returns the number of items contained within. This means that the length function has an arity of 1 and should only be passed one argument. The return value is always an number representing the count of items contained within the parameter that’s provided to the function.
It’s worth mentioning that
len works on any sequence or collection in Python. This means you can also use it on Strings, Dictionaries, and Sets too!
name = "Brad" print("My name is ", len(name), " characters long.")
Hopefully now you’re able to successfully find the length of a list with Python! If you like to learn more about Python, you can find my posts on the language here!