Why does Python code use len() function instead of a length method?
I know that python has a
len() function that is used to determine the size of a string, but I was wondering why it's not a method of the string object.
Ok, I realized I was embarrassingly mistaken.
__len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see
__len__ as the name instead of just len.
Strings do have a length method:
The protocol in Python is to implement this method on objects which have a length and use the built-in
len() function, which calls it for you, similar to the way you would implement
__iter__() and use the built-in
iter() function (or have the method called behind the scenes for you) on objects which are iterable.
See Emulating container types for more information.
Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment
Why does Python code use len() function instead of a length method , Why does Python use methods for some functionality (e.g. list.index()) but First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much (b) When I read code that says len(x) I know that it is asking for the length of something. Also note that many functions are defined in terms of informal interfaces; for� Python len() The len() function returns the number of items (length) in an object.
Jim's answer to this question may help; I copy it here. Quoting Guido van Rossum:
First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI:
(a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into xa + xb to the clumsiness of doing the same thing using a raw OO notation.
(b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method.
Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/
Why does Python use methods for some functionality (e.g. list.index , You can use len function to optimize the performance of the program. The number of elements stored in the object is never calculated, so len� Python len() Function Built-in Functions. Example. When the object is a string, the len() function returns the number of characters in the string. Syntax. len
There is a
>>> a = 'a string of some length' >>> a.__len__() 23 >>> a.__len__ <method-wrapper '__len__' of str object at 0x02005650>
Python string length, In this tutorial, we'll go over several different functions that we can use to work with If we are asking for a post code we will only want to accept a numeric string, but Using the str.isnumeric() method on the string 5 returns a value of True , while whitespace characters, and symbols — will be counted by the len() function. A demo of getting the string length without using len() method. Well, using the length method for getting the length of the string is the most convenient way and that should be used in your programs. However, as strings are iterable in Python, you may use this to get the length of the string without using the len() method: See online demo and code
Python is a pragmatic programming language, and the reasons for
len() being a function and not a method of
dict etc. are pragmatic.
len() built-in function deals directly with built-in types: the CPython implementation of
len() actually returns the value of the
ob_size field in the
PyVarObject C struct that represents any variable-sized built-in object in memory. This is much faster than calling a method -- no attribute lookup needs to happen. Getting the number of items in a collection is a common operation and must work efficiently for such basic and diverse types as
However, to promote consistency, when applying
len(o) to a user-defined type, Python calls
o.__len__() as a fallback.
__abs__ and all the other special methods documented in the Python Data Model make it easy to create objects that behave like the built-ins, enabling the expressive and highly consistent APIs we call "Pythonic".
By implementing special methods your objects can support iteration, overload infix operators, manage contexts in
with blocks etc. You can think of the Data Model as a way of using the Python language itself as a framework where the objects you create can be integrated seamlessly.
A second reason, supported by quotes from Guido van Rossum like this one, is that it is easier to read and write
len(s) is consistent with unary operators with prefix notation, like
len() is used way more often than
abs(), and it deserves to be as easy to write.
There may also be a historical reason: in the ABC language which preceded Python (and was very influential in its design), there was a unary operator written as
#s which meant
String Functions in Python 3, Why does Python use indentation for grouping of statements? Why does Python use methods for some functionality (e.g. list.index()) but functions for other (e.g. len(list))?. Why is join() a string method instead of a list or tuple method? ( b) When I read code that says len(x) I know that it is asking for the length of something� Well, len(s) is a built-in Python method which returns the length of an object. Now __len__() is a special method that is internally called by len(s) method to return the length of an object. So, when we call len(s) method, s.__len__() is what actually happening behind the scenes to calculate the length. The Python len() function can be
met% python -c 'import this' | grep 'only one' There should be one-- and preferably only one --obvious way to do it.
Design and History FAQ — Python 3.8.5 documentation, The methods that add, subtract, or rearrange their members in place, and don't return a The latter function is implicitly used when an object is written by the print() function. Truth Value Testing�. Any object can be tested for truth value, for use in an if or while condition or as The integer is represented using length bytes. Python's len() method can be used to easily find the length of a string. It's a simple and quick way to measure the length of a string (the number of characters) without having to write a lot of code. The syntax for using the len() method is fairly straightforward, and hard to mess up -- even beginner Python coders should be able to handle it.
Built-in Types — Python 3.8.5 documentation, Instead, convert to a floating point number using the abs() function if appropriate. (3)(4). s[i:j:k]. slice of s from i to j with step k. (3)(5). len(s). length of s. min(s) For performance sensitive code, it is preferable to use the str.join() method which � len() function is an inbuilt function in Python programming language that returns the length of the string. Below is the Python implementation of the len() method
5. Built-in Types — Python 2.7.18 documentation, The len() function returns the number of items (length) in an object. len(testByte )). Run Code. Output Length of is 0 Length of Python is 6 Length of b'Python' is 6 Length of b'\x01\x02\x03' is 3 Internally, len() calls object's __len__ method. It was decided at some point long ago getting the length of something should be a function and not a method code, reasoning that len(a)'s meaning would be clear to beginners but a.len() would not be as clear. When Python started __len__ didn't even exist and len was a special thing that worked with a few types of objects. Whether or not the
Python len(), The len function returns the number of characters in a string: The loop condition is index < len(fruit), so when index is equal to the length of the string, the Instead of producing the output Jello, world!, this code produces the runtime error The most concise and powerful way to format a string in Python is to use the string� This tutorial explains how to use len function to get length of string and number of element in a list in python. This zrticle also explains how to calculate length of string without using len() function in Python.