by BehindJava

What are Methods in Python with Syntax and Examples

Home » python » What are Methods in Python with Syntax and Examples

In this tutorial we are going to learn about Methods in Python with Syntax and Examples.

We’ve already seen a few example of methods when learning about Object and Data Structure Types in Python. Methods are essentially functions built into objects. Later on we will learn about how to create our own objects and methods using Object Oriented Programming (OOP) and classes.

Methods perform specific actions on an object and can also take arguments, just like a function. This tutorial will serve as just a brief introduction to methods and get you thinking about overall design methods that we will touch back upon when we reach OOP in the course.

Methods are in the form:

object.method(arg1,arg2,etc...)

You’ll later see that we can think of methods as having an argument ‘self’ referring to the object itself. You can’t see this argument but we will be using it later on in the course during the OOP lectures.

Let’s take a quick look at what an example of the various methods a list has:

# Create a simple list
lst = [1,2,3,4,5]

Fortunately, with iPython and the Jupyter Notebook we can quickly see all the possible methods using the tab key. The methods for a list are:

  • append
  • count
  • extend
  • insert
  • pop
  • remove
  • reverse
  • sort

Let’s try out a few of them:

append() allows us to add elements to the end of a list:

lst.append(6)
lst

Output-
[1, 2, 3, 4, 5, 6]

Great! Now how about count()? The count() method will count the number of occurrences of an element in a list.

# Check how many times 2 shows up in the list
lst.count(2)

Output-
1

You can always use Shift+Tab in the Jupyter Notebook to get more help about the method. In general Python you can use the help() function:

help(lst.count)

Output-
Help on built-in function count:
count(...) method of builtins.list instance
    L.count(value) -> integer -- return number of occurrences of value