Flat_Eric Contemplating Data Type Conversions

Methods vs. Functions

See? Simple!

Methods vs Functions

We have already used a lot of functions throughout this course. Built in functions that Python provides like print(), min(), max(), len(), range(), enumerate(), list(), int(), str() and many more. You can find the full list of Python's built in functions in the official documentation:

Python Built in Functions

We have also learned how to create our own functions to do whatever we need:

All of these are functions. We call them by typing the function name followed by parentheses that either contain arguments or are left empty.

Methods

Methods work differently. Instead of being called by name on their own, methods are called using dot notation. You type the data first, then a dot, then the method name and parentheses. For example:

"test".capitalize()

You have already used methods throughout this course. String methods, list methods, dictionary methods and set methods. Here is a full reference for Python string methods:

Python String Methods Reference

If you type a string in your editor and add a dot after it, Python will show you a list of every method available for that data type:

Python interpreter showing a list of string methods

The Key Difference

The most important thing to understand about methods is this: a method belongs to whatever is to the left of the dot. The method is owned by the data it is called on. It cannot exist on its own.

If you try to call a method like a function, for example typing capitalize() on its own without anything to the left of it, Python will throw a NameError because capitalize() is not a function. It does not exist independently. It only exists as a method that belongs to a string.

Methods are available on all different data types. Strings, lists, tuples, dictionaries and sets all have their own set of methods designed specifically for that data type. A list method will not work on a string and a string method will not work on a list.

The best way to learn methods is to use them. Try them, break them, read what they do in the documentation and experiment. The official Python documentation is your best resource and one you will return to constantly throughout your coding journey:

Python Official Documentation

Time to experiment!

Coding Exercises (VS Code) Instructions:

Exercise 1: String Methods

Exercise 2: List Methods

Exercise 3: Dictionary Methods

Exercise 4: Research Challenge

Exercise 5: Methods vs Functions

Don't Forget to commit and Push!

This course was built by DevSTEM - we turn teaching materials into interactive web courses like this one.

Build your own course