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")
And now:
len(items)
returns 3.
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
len(s)
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:
items.__len__()
returns 3.
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.
Also, do not do:
if len(items):
...
Instead, simply do:
if items: # Then we have some items, not empty!
...
or
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.
Источник
In this article, we will discuss how we get the number of elements in a list.
Example:
Input: [1,2,3,4,5]
Output: 5
Explanation: No of elements in the list are 5
Input: [1.2 ,4.5, 2.2]
Output: 3
Explanation: No of elements in the list are 3
Input: [“apple”, “banana”, “mangoe”]
Output: 3
Explanation: No of elements in the list are 3
Before getting the Number of Elements in the Python List, we have to create an empty List and store some items into the list.
There are three methods to get the number of elements in the list, i.e.:
- Using Python len( ) function
- Using for loop
- Using operator length_hint function
Using Len() function to Get the Number of Elements
We can use the len( ) function to return the number of elements present in the list.
Python3
elem_list = [1, 2, 3, 4]
print(elem_list)
print("No of elements in list are:", len(elem_list))
Output:
[1, 2, 3, 4]
No of elements in list are: 4
Time Complexity: O(1)
Auxiliary Space: O(1)
Using for loop Get the Number of Elements
We can declare a counter variable to count the number of elements in the list using a for loop and print the counter after the loop in Python gets terminated.
Python3
item_list = [1, 2, 3, 4]
count = 0
for i in item_list:
count = count+1
print(item_list)
print("No of elements in the list are:", count)
Output:
[1, 2, 3, 4]
No of elements in the list are: 4 Подробнее ...