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 OverflowThe 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
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.
[Python] How to find the length of elements in a list?
(C#) find length of a List<String>?
List input in C and length argument - Code Golf Meta Stack Exchange
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]]>
Videos
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 elementI 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!
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.
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.