Methods - Hsanokklis/2023-2024-Tech-journal GitHub Wiki

Methods

A method is the same thing as a function, except it is "called on" a value. For example, if a list value were stored in spam, you would call the index() list method on that list like so: spam.index('hello'). The method part comes after the value, separated by a period.

Each data type has its own set of methods.

  • The list data type (for example), has several useful methods for finding, adding, removing and otherwise manipulating values in a list.

Finding a value in a List with the index() Method

List values have an index() method that can be passed a value and if that value exists in the list, the index of the value is returned. If the value isn't in the list, then Python produces a ValueError error.

image

When there are duplicates of the same thing in a list the index of its appearance is returned.

image

The value of Pooka is returned as 1 and not 3, because it shows up in index[1] first.

Adding Values to Lists with the append() and insert() Methods

To add new values to a list, use the append() and insert() methods.

image

The spam.append('moose') method call adds the argument to the end of the list.

Essentially adding it to the list. So now instead of 3 values in the list there are 4.

image

The spam.insert(1, 'chicken') puts the chicken value in index one.