Python Forum

Full Version: Equivalent in List, of the "len(string)"
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all! Which is the keyword that makes python count the number of items in a List ??
You can get the length of the list: len(object)
(Jul-18-2018, 05:23 AM)sylas Wrote: [ -> ]Hi all! Which is the keyword that makes python count the number of items in a List ??
To clarify, "keyword" has a technical meaning in Python, and includes things like return, yield and in Python 2, print. However, len is a built-in function. The difference between the two can be subtle, but programming is a technical discipline and your post count is high enough that don't want anyone stumbling across this in the future to misread what they see here.

(wavic's answer is obviously the useful answer, but I'm feeling pedantic I guess.)
(Jul-18-2018, 05:23 AM)sylas Wrote: [ -> ]Hi all! Which is the keyword that makes python count the number of items in a List ??

len(string) isn't a thing, as is implied by the subject. It's len(iterable). Strings, lists, dicts, ranges, etc are iterables, and len works with them just fine :)
(Jul-19-2018, 09:01 PM)nilamo Wrote: [ -> ]It's len(iterable). Strings, lists, dicts, ranges, etc are iterables, and len works with them just fine :)
I almost said this, but it's not always true -
Output:
>>> len(x for x in range(0)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: object of type 'generator' has no len()
Generators are iterable, but you can't get their length. You'd have to turn them into a collection (list or tuple in this case) to get their length, but some generators have infinite length.