The len() function can be used with several different types in Python - both built-in types and library types. For example:

>>> len([1, 2, 3])
3
Answer from gnud on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › find-the-length-of-a-list-in-python
How to find the length of a list in Python | DigitalOcean
July 25, 2025 - The most direct, efficient, and “Pythonic” way to get the number of items in a list is by using Python’s built-in len() function. This function is a core part of the language and is designed to be highly optimized for this exact purpose. The len() function is universal and can be used ...
Top answer
1 of 11
2991

The len() function can be used with several different types in Python - both built-in types and library types. For example:

>>> len([1, 2, 3])
3
2 of 11
322

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.

Discussions

[Python] How to find the length of elements in a list?
Try if len(element) == 2: len returns the number of elements in a list, when applied to a string it returns the number of characters. More on reddit.com
🌐 r/learnprogramming
2
0
November 23, 2016
(C#) find length of a List<String>?
This is a common error. But stop to think about it. Let's say I have this: List mylist = new List(); mylist.Add("test1"); mylist.Add("test2"); How many items are there? 2 right. And since indexes are zero based it would be: mylist[0] = "test1" mylist[1] = "test2" Now, take a look at your look again and see if you can find the problem. More on reddit.com
🌐 r/learnprogramming
10
7
January 13, 2012
List input in C and length argument - Code Golf Meta Stack Exchange
Sidenote: This might be better ... get the length of a list in C. \$\endgroup\$ ... \$\begingroup\$ this deleted answer to the Default input/output question proposed the same thing. It was down-voted, then deleted by the owner. \$\endgroup\$ ... I estimate 15% of my Python golfs with ... More on codegolf.meta.stackexchange.com
🌐 codegolf.meta.stackexchange.com
How do I convert a Python list of tf.Tensors (of variable length) to a tf.Tensor of those tensors

Can you try this?

a = tf.convert_to_tensor([1,2])

b = tf.convert_to_tensor([1,2,3])

c = tf.convert_to_tensor([1,2,3,4])

l=[a,b,c]

tf.ragged.stack(l)

This gives the output as

<tf.RaggedTensor [[1, 2], [1, 2, 3], [1, 2, 3, 4]]>

More on reddit.com
🌐 r/tensorflow
4
6
April 16, 2021
🌐
W3Schools
w3schools.com › python › gloss_python_list_length.asp
Python List Length
MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit · Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary
🌐
Edureka
edureka.co › blog › python-list-length
How to Get the Length of List in Python? | Edureka
November 27, 2024 - But what if you want to count the number of items in a list? That’s why it’s important to determine how long the list is. ... In this guide, we’ll learn different ways to find out how long a list is easily. Whether you’re a beginner or an experienced programmer, join me as we unravel the simplicity of Python’s built-in functions and techniques to get the length ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-ways-to-find-length-of-list
How To Find the Length of a List in Python - GeeksforGeeks
May 2, 2025 - Explanation: len() function directly returns the total number of elements present in the list. This approach involves manually iterating through the list and counting each element.
🌐
Hostman
hostman.com › tutorials › how to get the length of a list in python
How to Find the Length of a List in Python: Quick Guide | Hostman
July 17, 2025 - You can determine a list’s length in Python with a for loop. The idea is to traverse the entire list while incrementing a counter by 1 on each iteration. Let’s wrap this in a separate function: def list_length(list): counter = 0 for i in ...
Price   $
Address   1999 Harrison St 1800 9079, 94612, Oakland
🌐
Reddit
reddit.com › r/learnprogramming › [python] how to find the length of elements in a list?
r/learnprogramming on Reddit: [Python] How to find the length of elements in a list?
November 23, 2016 -

I need to write a function that is passed in a list of strings, and returns a new list with all the strings of the original list that had a length of two. So the list: list = ['oh','hello','there','!!'] Will return: ['oh','!!'] I've absolutely hit a brick wall here. I'm positive I need to use the len() function, but no matter how I try to implement it, I keep getting how many elements are in the list. Please help if y'can!

def sift_two(theOtherList):
    for element in theOtherList:
       if element == len(2):
            return element
Find elsewhere
🌐
Carmatec
carmatec.com › home › finding the length of a list in python with examples
Finding the Length of a List in Python With Examples
December 31, 2024 - # Manual counting my_list = [1, 2, 3, 4, 5] counter = 0 for item in my_list: counter += 1 print("The length of the list is:", counter) ... While this method works, it is less efficient and not recommended for large datasets. ... You can achieve the same result with a more Pythonic approach using list comprehension.
🌐
Codefinity
codefinity.com › courses › v2 › 102a5c09-d0fd-4d74-b116-a7f25cb8d9fe › 39cc7383-2374-4f3f-b322-2cb0109e6427 › fe628b40-c2e6-44d8-8d58-49dfba369282
Learn Python List Length: Measuring and Managing List Size | Mastering Python Lists
Python provides the len() function, which returns the total number of items in a list. ... A nested list is considered a single item. The len() function doesn't count the individual items inside a nested list as separate items of the main list.
🌐
Great Learning
mygreatlearning.com › blog › it/software development › how to find length of list in python
How to Find Length of List in Python
June 27, 2025 - Using a loop (less common but illustrates concepts): You can count elements by iterating through the list. Let’s look at each one. The len() function is a built-in Python function. It takes an object as an argument and returns its length (the ...
🌐
CodeConverter
codeconverter.com › articles › python-length-of-list
Getting the Length of a List in Python | CodeConverter Blog
February 12, 2026 - The function returns the number of elements in the list, which is then printed to the console. But have you ever wondered how len() actually works? Well, it's quite simple really. When you call len() on a list, Python internally calls the list's __len__() method.
🌐
Sprintzeal
sprintzeal.com › blog › python-list-length
Find the Length of List in Python
April 4, 2023 - There are two commonly employed and fundamental methods to calculate what the total length is for Python: ... The len() method is the most commonly used and straightforward approach for determining the length of any list.
🌐
iO Flood
ioflood.com › blog › python-length-of-list
Finding the Length of a List in Python (With Examples)
August 21, 2024 - Then, we used the len() function, which returned the number of elements in the list, which is 5. The len() function is a straightforward and efficient way to find the length of a list in Python.
🌐
Replit
replit.com › home › discover › how to find the length of a list in python
How to find the length of a list in Python
February 6, 2026 - Python lists internally track their own size, so calling len() doesn't involve iterating through the elements. It's an O(1) operation—meaning its speed is constant, regardless of the list's size—as it just retrieves a stored value.
🌐
Cherry Servers
cherryservers.com › home › blog › cloud computing › how to get the length of a list in python
How to Get the Length of a List in Python | Cherry Servers
November 7, 2025 - Deploy and scale your Python projects effortlessly on Cherry Servers' robust and cost-effective dedicated or virtual servers. Benefit from an open cloud ecosystem with seamless API & integrations and a Python library. ... We will focus on five different methods that can be used to find the length of a list in Python.
🌐
DataCamp
datacamp.com › tutorial › python-list-size
Python List Size: 8 Different Methods for Finding the Length of a List in Python | DataCamp
February 7, 2024 - For the purposes of this tutorial, we will use a simple list to demonstrate each method. Consider the list my_list, defined as follows: # Define a sample list to be used throughout the tutorial my_list = ["I", "Love", "Learning", "Python"] This list, albeit simple, serves as a perfect candidate to illustrate various techniques for determining its length...
🌐
Reddit
reddit.com › r/learnprogramming › (c#) find length of a list?
r/learnprogramming on Reddit: (C#) find length of a List<String>?
January 13, 2012 -

I am attempting to grab a List<String> and iterate through each string in the list then Iterate through each Character in each string.

I can get the length of the list, but I am having a hard time getiing the length of the String.

List<String> myList;
 for (int y = 0; y <= myList.Count(); y++)
        {
 for (int x = 0; x <= myList[y].Length ; x++)
{

And I keep getting an index out of bounds error. I know I am probably going about this all wrong. So I will ask here for advice and come back tomorrow with a fresh head and see if it makes any more sense.

Thanks!

🌐
W3Schools
w3schools.com › c › c_arrays_size.php
C Get the Size of an Array
Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.
Top answer
1 of 6
14

Not for all languages

I estimate 15% of my Python golfs with list input could be shortened by taking in its length, if that were allowed. Hundreds of golfs in mainstream languages could be improved by mechanically replacing "len(l)" or similar with an input parameter.

These submissions strongly suggest that golfers wouldn't guess this to be allowed without knowing the rule specifically. This is a hidden rule of the worst kind -- broadly useful, unexpected, and likely to make golfs more boring on average.

I'm sympathetic to the problems languages like C have with cumbersome input processing, especially as they already have many disadvantages. Golfing languages can be designed around such issues, but C is stuck with them.

But, I want to avoid the trend of giving all languages an easy extra workaround because one language really wants it. The result is a laundry list of liberties with input that go beyond taking it conveniently and naturally for the language, to doing parts of the golfing task in the input format, justified by citing obscure meta threads about other languages.

I'd rather say that this is a property of C that golfers need to deal with, or that a C-specific rule be made. Either one would be better than changing the rules for all languages.

2 of 6
12

This is an interesting indication of the way PPCG has changed since the early days. I remember when a lot of questions included the length as a separate input and people commented with requests to make it optional because their high-level languages didn't need it.

In most high-level languages an array is effectively a struct with a pointer and a length. I don't see that there's any point to creating a standard struct template. However, it does seem perfectly reasonable to interpret "array" in a question as meaning "pointer and length, as encapsulated in your language". In the case of C the simplest "encapsulation"* is as two variables.

* Yes, I get the point that it's not really encapsulation if you can split them up, hence the scare quotes. But such pedanticism is not the point here.

🌐
Quora
quora.com › How-do-you-check-the-length-of-a-list-in-Python
How to check the length of a list in Python - Quora
It simply means to count the number of elements in the list. We will look at two simple methods to find the lengths of a list. ... First we will look at a very basic method that anyone with a little knowledge of the Python language will be able to grasp. We will use a loop and a counter in this technique.