- Get Number of Elements in a List in Python
- Method 1: Using the len() function to get the number of items:
- Method 2: Using the length_hint function to obtain the number of items:
- Method 3: Using the for loop to obtain the number of items:
- Method 4: Get the Number of Items in a List Containing Other Lists:
- Method 5: Using the list of a list to obtain the number of items:
- Method 6: Get the Number of Unique Elements in a List:
- How do I get the number of elements in a list (length of a list) in Python?
- 11 Answers 11
- How do I get the length of a list?
- Explanation
- From the docs
- Builtin types you can get the len (length) of
- Do not use len to test for an empty or nonempty list
Get Number of Elements in a List in Python
Like an array, a list is a data structure that is mutable or changeable and stores elements in an ordered sequence. Users can term each element or value as «items.» A string that contains characters and users write them within quotes.
So in simple words, users can define a list like a string that has elements inside square brackets «[ ]» and separated by commas [,]. This tutorial will discuss how users can get the number of elements in a list in Python using the different functions and methods.
What are lists in Python?
Users can create a list by adding different elements inside square brackets. A list can have items of distinct data types and any number of items. Also, users can add a list as an item inside another list called the nested list. Python lists are simply like dynamically sized arrays, having items with different data types.
Users are free to use any of the different methods in Python to find the number of elements of a list. The methods may differ based on whether users like to count all the lists within the main list as a single element, find the number of elements in the nested lists, or whether they need to count all the unique elements.
The functions like len(), length_hint, and a for loop will let users get the count of the number of elements in a list.
Example of the list is as follows:
a = [1, 297.5, "Hello", False] # Here, we are printing the list print(a)
Different Methods to obtain the number of items in a List:
Method 1: Using the len() function to get the number of items:
The built-in len() function will allow Python users to get the count of the items in a list.
Code Snippet:
# Here, we are declaring the list of items my_list = ["Hey", 2, True, 3954.65, "Dragon", 3434] # Here, we are printing the list print(my_list) # use the len() function to obtain the number of elements print("The number of elements in the list are:", len(my_list))
Explanation:
The len() function returns the number of items present in the list.
Method 2: Using the length_hint function to obtain the number of items:
Another way of getting the number of elements of a list is using the length_hint function of Python.
Code Snippet:
from operator import length_hint list = ["Hey", 2, True, 3954.65, "Dragon", 3434] print(length_hint(list))
Explanation:
In the console, we can see that the function returns the total number of elements the list contains.
Method 3: Using the for loop to obtain the number of items:
Another technique with which users can do this is to make a function that loops through the list using a for loop. First, users need to initialize the count of the items to zero, and every time, the compiler will iterate through these items in the list, i.e., a loop iteration will execute, and the count increases by 1.
The loop execution will end when it finishes iterating over all the elements. Finally, the output will represent the total number of items present in the list:
Code Snippet:
# Here, we are declaring the list of items list = ["Hey", 2, True, 3954.65, "Dragon", 3434] # Here, we are declaring a counter variable a = 0 # The for loop will iterate on items and keep incrementing the value of the count for i in list: # It will increment the count value a = a+1 # Here, we will print the items on the list print(list) print("The total number of items in the list are:", a)
Explanation:
The for loop will iterate over all the items in the list and finally returns the total count. But using a for loop to get the number of elements is a much more rambling solution than the len() function.
Method 4: Get the Number of Items in a List Containing Other Lists:
This method will help users count the number of items in the nested list and the main list. Here, users will use the for loop that initializes the count variable to zero and loops through the items.
Code Snippet:
a = [[34, 5, 23, 74], [234.4, 234.56, ""], [], [10, 20], "char", [True, "Hello", 69], ""] def get_all_elements_in_list_of_lists(list): i = 0 for ele in a: i += len(ele) return i print("Total number of elements in the list of lists: ", get_all_elements_in_list_of_lists(a))
Explanation:
This method brings all the nested list items, including the number of characters inside the string. We can see that each character of the «Python» string counts towards the total number of items because the len() function operates on the string by returning all the characters.
Again, we can see that the empty list did not affect the total count. It is because in every Python for loop, users consider the length of the existing nested list. Since the length of the empty list is zero, the length count will increase by zero.
Method 5: Using the list of a list to obtain the number of items:
Users can also use the built-in len() function to count the number of the nested list inside a list.
Code Snippet:
a = [[34, 5, 23, 74], [234.4, 234.56, ""], [], [10, 20], [True, "Hello", 69], "Python"] total = len(a) print("The total number of elements in the list of lists: ", total)
Explanation:
The len() function will count the nested list and the string as a single element. It returns the final count of list items.
Method 6: Get the Number of Unique Elements in a List:
Often, users can see that they have added multiple items inside a list where there are duplicate items. If users want to get the number of elements without counting the same items, they can use this set() function, which rejects all the duplicate list items during its count.
Code Snippet:
list = [1, 4358.43, "", True, 2, 1, "Hello", True] ele = len(list) ele1 = len(set(list)) print("The number of elements in the list: ", ele) print("The number of unique elements in the list: ", ele1)
Explanation:
The set() function does not need any parameter, and we can see in the console that the list contains eight items and five unique items.
Conclusion:
We hope this article has discussed different ways to get the total count of items in a list and the nested lists.
Nested lists are those lists that are items or elements of another list. A Python program can have multiple lists, one inside the other. So, according to the requirement, users can use the above methods to get the number of elements of a list.
- Null Object in Python
- TypeError: ‘int’ object is not subscriptable
- pip is not recognized
- Python Comment
- Python Continue Statement
- Python Max() Function
- Python : end parameter in print()
- Python String Concatenation
- Python Enumerate
- Python New 3.6 Features
- Python eval
- Install Opencv Python PIP Windows
- Python String Title() Method
- Python Print Without Newline
- Python Split()
- Ord Function in Python
- Bubble Sort in Python
- Python list append and extend
- Compare Two Lists in Python
- Pangram Program in Python
How do I get the number of elements in a list (length of a list) in Python?
You are obviously asking for the number of elements in the list. If a searcher comes here looking for the size of the object in memory, this is the actual question & answers they are looking for: How do I determine the size of an object in Python?
@RussiaMustRemovePutin The title of this question was subsequently edited, so it seems unlikely that people with that question would end up here as it stands.
11 Answers 11
The len() function can be used with several different types in Python — both built-in types and library types. For example:
How do I get the length of a list?
To find the number of elements in a list, use the builtin function len :
items = [] items.append("apple") items.append("orange") items.append("banana")
Explanation
Everything in Python is an object, including lists. All objects have a header of some sort in the C implementation.
Lists and other similar builtin objects with a «size» in Python, in particular, have an attribute called ob_size , where the number of elements in the object is cached. So checking the number of objects in a list is very fast.
But if you’re checking if list size is zero or not, don’t use len — instead, put the list in a boolean context — it is treated as False if empty, and True if non-empty.
From the docs
Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).
len is implemented with __len__ , from the data model docs:
object.__len__(self)
Called to implement the built-in function len() . Should return the length of the object, an integer >= 0. Also, an object that doesn’t define a __nonzero__() [in Python 2 or __bool__() in Python 3] method and whose __len__() method returns zero is considered to be false in a Boolean context.
And we can also see that __len__ is a method of lists:
Builtin types you can get the len (length) of
And in fact we see we can get this information for all of the described types:
>>> all(hasattr(cls, '__len__') for cls in (str, bytes, tuple, list, range, dict, set, frozenset)) True
Do not use len to test for an empty or nonempty list
To test for a specific length, of course, simply test for equality:
if len(items) == required_length: .
But there’s a special case for testing for a zero length list or the inverse. In that case, do not test for equality.
if items: # Then we have some items, not empty! .
if not items: # Then we have an empty list! .
I explain why here but in short, if items or if not items is more readable and performant than other alternatives.
While this may not be useful due to the fact that it’d make a lot more sense as being «out of the box» functionality, a fairly simple hack would be to build a class with a length property:
class slist(list): @property def length(self): return len(self)
>>> l = slist(range(10)) >>> l.length 10 >>> print l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Essentially, it’s exactly identical to a list object, with the added benefit of having an OOP-friendly length property.
As always, your mileage may vary.
just so you know, you can just do length = property(len) and skip the one line wrapper function and keep the documentation / introspection of len with your property.
Besides len you can also use operator.length_hint (requires Python 3.4+). For a normal list both are equivalent, but length_hint makes it possible to get the length of a list-iterator, which could be useful in certain circumstances:
>>> from operator import length_hint >>> l = ["apple", "orange", "banana"] >>> len(l) 3 >>> length_hint(l) 3 >>> list_iterator = iter(l) >>> len(list_iterator) TypeError: object of type 'list_iterator' has no len() >>> length_hint(list_iterator) 3
But length_hint is by definition only a «hint», so most of the time len is better.
I’ve seen several answers suggesting accessing __len__ . This is all right when dealing with built-in classes like list , but it could lead to problems with custom classes, because len (and length_hint ) implement some safety checks. For example, both do not allow negative lengths or lengths that exceed a certain value (the sys.maxsize value). So it’s always safer to use the len function instead of the __len__ method!
And for completeness (primarily educational), it is possible without using the len() function. I would not condone this as a good option DO NOT PROGRAM LIKE THIS IN PYTHON, but it serves a purpose for learning algorithms.
def count(list): # list is an iterable object but no type checking here! item_count = 0 for item in list: item_count += 1 return item_count count([1,2,3,4,5])
(The list object must be iterable, implied by the for..in stanza.)
The lesson here for new programmers is: You can’t get the number of items in a list without counting them at some point. The question becomes: when is a good time to count them? For example, high-performance code like the connect system call for sockets (written in C) connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen); , does not calculate the length of elements (giving that responsibility to the calling code). Notice that the length of the address is passed along to save the step of counting the length first? Another option: computationally, it might make sense to keep track of the number of items as you add them within the object that you pass. Mind that this takes up more space in memory. See Naftuli Kay‘s answer.
Example of keeping track of the length to improve performance while taking up more space in memory. Note that I never use the len() function because the length is tracked:
class MyList(object): def __init__(self): self._data = [] self.length = 0 # length tracker that takes up memory but makes length op O(1) time # the implicit iterator in a list class def __iter__(self): for elem in self._data: yield elem def add(self, elem): self._data.append(elem) self.length += 1 def remove(self, elem): self._data.remove(elem) self.length -= 1 mylist = MyList() mylist.add(1) mylist.add(2) mylist.add(3) print(mylist.length) # 3 mylist.remove(3) print(mylist.length) # 2