Python List Length

To calculate a Python list length, use the built-in len() function.


For example, let’s calculate the length of a list of integers:

nums = [1,2,3]
l = len(nums)




Using the len() Function in Python

Python comes with a built-in len() function. This is the most common way to calculate the length of a list.

Python list length using the len() function

Actually, you are not restricted to using len() function only on lists. You can use len() on:

Here are some examples of calculating the lengths of each of these data types:

# Tuple
nums_tuple = (1, 2, 3, 4 ,5)
len(nums_tuple) # returns 5

# List
names_list = ["Alice", "Bob", "Charlie"]
len(names_list) # returns 3

# Dictionary
nums_dict = {"1": 1, "2": 2}
len(nums_dict) # returns 2

# Set
nums_set = {1, 2, 3, 4, 5, 6}
len(nums_set) # returns 6

# Range
num_range = range(100)
len(num_range) # returns 100

# Byte object
byte_obj = b'\x00\x04\x00'
len(byte_obj) # returns 3

A Naive Way to Calculate a Python List Length

Of course, if you’re practicing the basics of coding, you can use a loop to calculate the number of list elements.

For example, here’s a for loop that iterates a list of integers and increments a counter variable length to calculate the number of elements.

nums = [1, 2, 3, 4, 5]

length = 0
for _ in nums:
    length += 1

print(f"The lenght of a lits is {length}")


The lenght of a lits is 5

Keep in mind that doing it this way is impractical—you always have the len() function at your disposal.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

10+ Useful Python Tricks to Code Like a Pro


Python’s official Docs