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.

Answer from xnor on Stack Exchange
🌐
W3Schools
w3schools.com › python › gloss_python_list_length.asp
Python List Length
Getting Started Mean Median Mode ... Regression Grid Search Categorical Data K-means Bootstrap Aggregation Cross Validation AUC - ROC Curve K-nearest neighbors · Python DSA Lists and Arrays Stacks Queues Linked Lists Hash Tables Trees Binary Trees Binary Search Trees AVL Trees ...
🌐
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.
Discussions

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 get the number of elements in a list (length of a list) in Python? - Stack Overflow
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. ... Return the length ... More on stackoverflow.com
🌐 stackoverflow.com
[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 Program Length of Array
int is a 32-bit (= 4 byte) data type, so sizeof(array) returns the number of elements times the size in bytes of a single object. A common way of getting the length of an array in C is sizeof(array)/sizeof(array[0]). More on reddit.com
🌐 r/code
6
3
February 21, 2022
🌐
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 ...
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.

Top answer
1 of 11
2990

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
321

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.

🌐
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 - We will also cover more advanced topics such as nested lists, performance implications, and common errors to ensure you have a complete mastery of this concept. The built-in len() function is the single best and most efficient method to find the length of a list in Python.
🌐
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 - The length of a list refers to the number of elements in the list. There are several methods to determine the length of a list in Python. For example, consider a list l = [1, 2, 3, 4, 5], length of this list is 5 as it contains 5 elements in it.
Find elsewhere
🌐
Quora
quora.com › What-is-the-length-of-a-list-in-C
What is the length of a list in C++? - Quora
Iteration-based count (when needed ... compute length by iterating and counting: ... For other sequence containers: std::vector::size(), std::deque::size(), std::forward_list (since it’s singly linked) does not have size() until C++23; prior to C++23 use manual counting for std::forward_list. size_type is unsigned — be careful when mixing with signed integers to avoid warnings or incorrect comparisons. ... Professional programmer: PowerShell Rust Python C++/C# ...
🌐
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.
🌐
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.
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
🌐
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 ...
🌐
Sprintzeal
sprintzeal.com › blog › python-list-length
Find the Length of List in Python
April 4, 2023 - Len() accepts the name of the list, or list_name, as its parameters and calculates the list's length. The syntax for defining the"len"() function within Python is as follows:
🌐
Tutorialspoint
tutorialspoint.com › python › list_len.htm
Python List len() Method
Following is the syntax for the Python List len() method − · len(list) list − This is a list for which number of elements to be counted. This method returns the number of elements in the list.
🌐
Reddit
reddit.com › r/roguelikedev › what's the best way to make a variable-length list of items or monsters in c?
r/roguelikedev on Reddit: What's the best way to make a variable-length list of Items or Monsters in C?
July 13, 2021 -

TL/DR: Are linked lists the best solution for an Entity list in C or is there a better solution?

I'm currently in the process of refactoring a small tutorial roguelike I made in C in order to make the code conform to best practices. In my game I have a list of Items and a list of Monsters which I can iterate through in order to make monsters take turns or see if the player is able to pick up an Item. Until recently, I had these lists implemented simply as arrays of pointers with a respective int counter to keep count of how many Items or Monsters there were at any given time:

Item* items[15] = { NULL };
int n_items = 0;

The arrays were bounded with a hard-coded limit (15 in this example). This limit could easily be observed when creating a new level and keep the number of items below the max, but once the player was given the option to 'drop' items, this limit became a problem, as any item carried over from other levels and dropped in a newly created dungeon level would now be added back into the item array and could easily overflow it.

In order to solve this issue I've implemented a singly linked list struct as:

typedef struct List 
{
    union {
        Actor* actor;
        Item* item;
    };
    struct List* next;
} List;

This List struct uses the following function to add new Items to the list:

void appendItem(List* head, Item* item)
{
    List* temp = head;
    
    while (temp->next)
    {
        temp = temp->next;
    }
    temp->next = malloc(sizeof(List));
    temp = temp->next;
    temp->item = item;
    temp->next = NULL;
}

The list can now be initiated as:

List* items = malloc(sizeof(List));
items->item = NULL;
items->next = NULL;

And I can iterate through the list with:

List* temp = items;
while (temp = temp->next)
{
    checkSomething(temp->item);
}

This setup now allows me to forget about a limit on items or actors and just add them as needed. However, before I continue with this structure and refactor all other arrays to use this, I wanted to ask if anyone knows whether this would be the best solution for the problem of the item and monster lists in a C roguelike. I've delved into the original Rogue source code and saw that the THING union has a prev and next pointers so I believe that it uses a similar setup, but I don't know if that is a good modern C solution. If any C developers would share any best-practices that they know of regarding this issue, it would be much appreciated. Thanks for taking the time to read through this and for any reply!

TL/DR: Are linked lists the best solution for an Entity list in C or is there a better solution?

🌐
DEV Community
dev.to › bekhruzniyazov › creating-a-python-like-list-in-c-4ebg
Creating a Python-like list in C - DEV Community
August 11, 2021 - { // it is okay to use a fixed-sized array here because it is a temporary array char *temp_array[list->length + 1]; // + 1 is for a new element // adding the list->list elements to the temp_array for (int i = 0; i < list->length; i++) { temp_array[i] = list->list[i]; } // adding the new element to the temp_array temp_array[list->length] = string; // 0 is the first number, that's why "list->length" instead of "list->length + 1" // freeing the list->list (it should be allocated to make this function work) free(list->list); // allocating memory for list->list list->list = calloc(list->length + 1, sizeof(char *)); // I am using calloc instead of malloc here because it just makes the code cleaner, apart from that there is no difference between them // adding elements from temp_array to list->list for (int i = 0; i < list->length + 1; i++) { list->list[i] = temp_array[i]; } list->length++; }
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › find the length of a list in python
Find the Length of a List in Python - Spark By {Examples}
May 31, 2024 - # Get the length of a list using naive method technology = ['Spark','Pandas','Java','C++'] # Finding length of list # using loop count = 0 for i in technology: count = count + 1 print("Get length of list: " + str(count)) # Output: # Get length of list: 4 · You can use the length_hint function as part of the operator module in Python, and it provides an estimate of the number of elements in an iterable object.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › find-length-of-a-linked-list-iterative-and-recursive
Length of a Linked List (Iterative and Recursive) - GeeksforGeeks
Interview Corner · DSA Python · Last Updated : 10 Sep, 2025 · Given a Singly Linked List, the task is to find the Length of the Linked List. Examples: Input: LinkedList = 1->3->1->2->1 Output: 5 Explanation: The linked list has 5 nodes. Input: LinkedList = 2->4->1->9->5->3->6 Output: 7 Explanation: The linked list has 7 nodes.
Published   September 10, 2025