.append()


#1

This doesn’t apply directly to this section, but this is the section I am currently doing, and .append() came up. I was wondering what you would call objects like .append(). Are they functions?


#2

They’re called ‘methods’. They’re essentially pre built functions to make common tasks and data manipulation easier. Just google a languages methods to learn more about them.


#3

.append() in the context of a list is, as @hobratschk said, called a method.

A method is just a function that is part of an object, so if we use the list object for example then append() is just a function defined within the list object that you can call.

Don’t worry if the specifics of methods is a bit confusing for now. They’ll make more sense once you get to Lesson 11, “Introduction to Classes”, which will show you to how to create your own objects (or classes) in Python and give them their own methods. :slight_smile:


#4
>>> type([])
<class 'list'>
>>> isinstance([], list)
True
>>> 

Objects are instances of a class, as in the above case, [] is an instance of the list class. The class is a definition or blueprint of all instances declared in that context. Within the class are defined properties (attributes) and methods that each instance will inherit from its class constructor. It’s why we use dot notation when invoking the methods. They are treated in the context of the instance upon which they are being invoked.

You will learn that declaring an object instance is as simple as assigning the class to a variable, and passing in initial values to be associated only with that particular instance.

>>> a = list()
>>> type(a)
<class 'list'>
>>> isinstance(a, list)
True
>>> 

Now that a is a list instance, it has an .append() method.

>>> a.append(3)
>>> a
[3]
>>>

Lists can be concatenated to another list…

>>> a += [4,5,6]
>>> a
[3, 4, 5, 6]

which can also be done with a method for that purpose…

>>> a.extend([7,8,9])
>>> a
[3, 4, 5, 6, 7, 8, 9]
>>> 

The Python Docs have a complete reference archive listing all the methods related to the list class. Add this to your necessary reading as you progress and review.


#5

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