How to Determine Size of List in Python
Monday, Aug 12, 2024 | 3 minutes read | Update at Monday, Aug 12, 2024
Python provides the list
in order to store multiple items in a single variable. The list is a dynamic strucuter which can contain multiple items in different counts and type. In this tutorial we try to determine the size of the list in different ways. Here are 10 examples to determine the size of a list in Python:
-
Using
len()
function: The defacto and most used way to determine the size of the is usinglen()
function. The list is provided as paramter to thelen()
function and the size of the provided list is return as integer.my_list = [1, 2, 3, 4, 5] size = len(my_list) print(size) # Output: 5
-
Using a loop (manual count): Python provides the
for
loop which can be used to iterate over items in a list. We can manually count the items in a list by iterating over them and increase the counter.my_list = [1, 2, 3, 4, 5] count = 0 for _ in my_list: count += 1 print(count) # Output: 5
-
Using list comprehension with
len()
: Some lists may contains another list as items. These lists are called as nested lists. We can use thelen()
method andlist comprehension
in order to count a nested lists all items.my_list = [1, 2, 3, 4, 5] size = len([x for x in my_list]) print(size) # Output: 5
-
Using
sum()
with a generator expression: We can use thesum()
method with generator expression by iterating over all list items and sum with 1 with every item which will return size of the list.my_list = [1, 2, 3, 4, 5] size = sum(1 for _ in my_list) print(size) # Output: 5
-
Using recursion:
def list_size(lst): if not lst: return 0 return 1 + list_size(lst[1:]) my_list = [1, 2, 3, 4, 5] size = list_size(my_list) print(size) # Output: 5
-
Using
reduce()
fromfunctools
: We can use thereduce()
andfunctools()
methods in order to count list items and decide size of the list.from functools import reduce my_list = [1, 2, 3, 4, 5] size = reduce(lambda count, _: count + 1, my_list, 0) print(size) # Output: 5
-
Using a while loop with an iterator: We can determine the size of the loop with the
while
loop by counting all items one by one.my_list = [1, 2, 3, 4, 5] it = iter(my_list) count = 0 while True: try: next(it) count += 1 except StopIteration: break print(count) # Output: 5
-
Using
map()
withlen()
: Another usefull way is using themap()
andlen()
methods like below.my_list = [1, 2, 3, 4, 5] size = len(list(map(lambda x: x, my_list))) print(size) # Output: 5
-
Using
numpy
(for numerical lists): The 3rd party librarynumpy
also provides the method namedsize
we can simply determine the size of the list by providing the list to thenumpy.size()
method as parameter.import numpy as np my_list = [1, 2, 3, 4, 5] size = np.size(my_list) print(size) # Output: 5
These examples show different ways to determine the size of a list in Python, using both built-in functions and more custom approaches.