Why lower and len are treated different?


#1

Here is the example

parrot = "Norwegian Blue"
print parrot.lower()
print len(parrot)

why lower comes after variable and len comes before?

Strings and Console Output


#2

because len() is a function, where as .lower() is a string method. To explain the differences between methods and functions, you need to understand classes and functions.

So for now, you will just have to work through it. But its a good question :slight_smile:


#3

len absolutely could have been a method, and the way to define length is to implement a method named __len__

There are a lot of built-in operations that an object can have, such as iteration, length, indexing, string conversion. These behaviours are all implemented by methods using __dunder__ naming convention, they’re used to promise certain behaviour to python itself so that they can be used in cases like for-loops (iteration), or in some cases it’s the language that promises when the are invoked, like how __init__ is called when an object is created.

Methods only operate on their own value type, and they’re not making any promises to the language about how they behave.

Note that nothing’s stopping you from calling these directly, or having them do crazy things, it’s by no means enforced. They’re there to tell the language what can be done with your object


#4

@urbankind, the Introduction to Classes course later on in the Learn Python track will delve more deeply into this.


#5

One hundred thanks! Didn’t expect swift response and thank you guys for explaining briefly.


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.