0%

25- Methods in Python

Functions that belong to objects. Strings have them. Lists have them. Dictionaries have them. Everything in Python has methods. Learn to use them, and you unlock the power of objects.

You have already used many methods without even knowing it. “hello”.upper() is a method. my_list.append(x) is a method. my_dict.keys() is a method. A method is simply a function that belongs to an object. It is attached to a specific type of data. Strings have string methods. Lists have list methods. Dictionaries have dictionary methods. You call a method using dot notation: object.method_name(arguments). Methods are different from functions. Functions like len() and print() stand alone. Methods are attached to objects. They operate on the object they belong to. This is object-oriented programming in action.

🕯️ Magic Note

In Python, everything is an object. Even numbers and strings are objects. This means everything has methods. 42.bit_length() works on an integer. 3.14.is_integer() works on a float. Methods are everywhere once you start looking for them.

What Are Methods?
A method is a function that is defined inside a class and belongs to instances of that class. When you call a method, Python automatically passes the object itself as the first argument (usually called self). For now, you just need to know how to use methods. You will learn how to create your own methods (functions inside classes) in the OOP lessons later.

Python

# Calling methods on different types of objects

text = “python”

print(text.upper()) # PYTHON (string method)

numbers = [1, 2, 3]

numbers.append(4) # [1, 2, 3, 4] (list method)

person = {“name”: “Ali”}

print(person.keys()) # dict_keys([‘name’]) (dictionary method)

num = 42

print(num.bit_length()) # 6 (integer method)

💡 To see what methods an object has, use dir(object) in the Python interpreter. Or use help(object.method) for documentation.
String Methods (Review)
Strings have many useful methods. You learned these in Lesson 7. Here is a quick review.
MethodWhat It DoesExample
.upper()Converts to uppercase“hello”.upper() → “HELLO”
.lower()Converts to lowercase“HELLO”.lower() → “hello”
.strip()Removes whitespace from both ends” hi “.strip() → “hi”
.replace(old, new)Replaces substrings“cat”.replace(“c”, “b”) → “bat”
.split()Splits into a list“a,b,c”.split(“,”) → [“a”,”b”,”c”]
.join(iterable)Joins a list into a string“,”.join([“a”,”b”]) → “a,b”
.find(sub)Returns index of substring“hello”.find(“e”) → 1
.count(sub)Counts occurrences“hello”.count(“l”) → 2

Python

text = ” Python Programming “

print(text.strip()) # “Python Programming”

print(text.upper()) # ” PYTHON PROGRAMMING “

print(text.replace(“Python”, “Java”)) # ” Java Programming “

print(text.split()) # [“Python”, “Programming”]

List Methods (Review)
Lists are mutable and have many methods for modification. You learned these in Lesson 9.
MethodWhat It DoesExample
.append(x)Adds x to the end[1,2].append(3) → [1,2,3]
.insert(i, x)Inserts x at index i[1,3].insert(1,2) → [1,2,3]
.extend(iter)Adds all items from iterable[1,2].extend([3,4]) → [1,2,3,4]
.remove(x)Removes first occurrence of x[1,2,1].remove(1) → [2,1]
.pop(i)Removes and returns item at i[1,2,3].pop() → returns 3, list becomes [1,2]
.index(x)Returns index of first x[“a”,”b”,”c”].index(“b”) → 1
.sort()Sorts the list in place[3,1,2].sort() → [1,2,3]
.reverse()Reverses the list in place[1,2,3].reverse() → [3,2,1]

Python

tasks = [“write”, “test”]

tasks.append(“deploy”)

print(tasks) # [“write”, “test”, “deploy”]

numbers = [3, 1, 4, 1, 5]

numbers.sort()

print(numbers) # [1, 1, 3, 4, 5]

last = numbers.pop()

print(last) # 5

print(numbers) # [1, 1, 3, 4]

Dictionary Methods (Review)
Dictionaries have methods for accessing keys, values, and items. You learned these in Lesson 10.
MethodWhat It DoesExample
.keys()Returns all keys{“a”:1}.keys() → dict_keys([“a”])
.values()Returns all values{“a”:1}.values() → dict_values([1])
.items()Returns key-value pairs{“a”:1}.items() → dict_items([(“a”,1)])
.get(key, default)Returns value or defaultd.get(“b”, 0) → 0
.pop(key)Removes and returns valued.pop(“a”) → 1
.update(other)Merges another dictionaryd.update({“b”:2})

Python

person = {“name”: “Feloriya”, “age”: 25}

print(person.keys()) # dict_keys([“name”, “age”])

print(person.values()) # dict_values([“Feloriya”, 25])

print(person.get(“city”, “Tehran”)) # “Tehran” (default)

for key, value in person.items():

print(f”{key}: {value}”)

Tuple Methods
Tuples have only two methods because they are immutable.
MethodWhat It DoesExample
.count(x)Counts occurrences of x(1,2,2,3).count(2) → 2
.index(x)Returns index of first x(1,2,3).index(2) → 1

Python

colors = (“red”, “green”, “blue”, “green”)

print(colors.count(“green”)) # 2

print(colors.index(“blue”)) # 2

Set Methods
Sets have methods for adding, removing, and mathematical operations.
MethodWhat It DoesExample
.add(x)Adds x to the sets.add(4)
.remove(x)Removes x (error if missing)s.remove(4)
.discard(x)Removes x (no error if missing)s.discard(4)
.union(other)Returns union (AB)A.union(B)
.intersection(other)Returns intersection (A & B)A.intersection(B)
.difference(other)Returns difference (A – B)A.difference(B)

Python

A = {1, 2, 3}

B = {3, 4, 5}

A.add(6)

print(A) # {1, 2, 3, 6}

print(A.union(B)) # {1, 2, 3, 4, 5, 6}

print(A.intersection(B)) # {3}

A.discard(6) # No error even if 6 not there

Integer and Float Methods
Numbers also have methods, though they are less commonly used.

Python

num = 42

print(num.bit_length()) # 6 (bits needed to represent 42)

print(num.to_bytes(2, “big”)) # b’\x00*’ (convert to bytes)

pi = 3.14

print(pi.is_integer()) # False

print(pi.as_integer_ratio()) # (157, 50) (fraction representation)

Method Chaining
Because methods return objects, you can chain them together. This is called method chaining.

Python

text = ” hello world “

# Without chaining (verbose)

cleaned = text.strip()

uppercased = cleaned.upper()

replaced = uppercased.replace(“WORLD”, “PYTHON”)

print(replaced) # “HELLO PYTHON”

# With chaining (elegant)

result = text.strip().upper().replace(“WORLD”, “PYTHON”)

print(result) # “HELLO PYTHON”

# Chaining with list methods

numbers = [3, 1, 4, 1, 5]

numbers.sort()

numbers.reverse()

# But note: sort() and reverse() return None, so they cannot be chained

⚠️ Not all methods return an object that supports further methods. Methods that modify in place (like .sort() and .append()) often return None and cannot be chained. Methods that return new objects (like .upper() and .strip()) can be chained.
Methods vs Functions: When to Use Which
Some operations are available as both functions and methods. For example, len() is a function, not a method, because it works on many types.
OperationFunctionMethodWhy
Get lengthlen(obj)obj.len() (no)Function works on all types
Convert to stringstr(obj)obj.__str__()Usually use str() function
Type checktype(obj)obj.__class__Usually use type() function
String to upperN/A“hi”.upper()Only strings have it
List appendN/A[1,2].append(3)Only lists have it

Python

# Functions (standalone)

numbers = [1, 2, 3]

print(len(numbers)) # 3 (function)

print(type(numbers)) # <class ‘list’> (function)

# Methods (attached)

text = “hello”

print(text.upper()) # “HELLO” (string method)

numbers.append(4) # list method

🕯️ Magic Note

Python uses a consistent rule: functions are for operations that make sense across many types. Methods are for operations that are specific to one type. len() works on lists, strings, tuples, dictionaries, and sets. .upper() only makes sense for strings.

Finding Available Methods
Use dir() to see all methods of an object. Use help() for documentation.

Python

# In Python interpreter:

# >>> dir(“hello”)

# [‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, …]

# >>> help(“hello”.upper)

# Help on built-in function upper:

# upper() method of builtins.str instance

# Return a copy of the string converted to uppercase.

💡 In a Jupyter notebook or IPython, you can type “hello”.upper? for quick help. Or use tab completion to see available methods.
Special Methods (Dunder Methods)
Methods with double underscores at the beginning and end are called “dunder” (double underscore) methods. They are special methods that Python calls automatically. You usually do not call them directly.

Python

# These are dunder methods (not usually called directly)

# __init__, __str__, __repr__, __len__, __add__, etc.

# Python calls them automatically:

x = 5

y = 3

print(x + y) # Calls x.__add__(y) behind the scenes

print(len([1,2])) # Calls the list’s __len__ method

print(str(42)) # Calls 42.__str__()

🕯️ Magic Note

You will learn to create your own dunder methods when you study object-oriented programming. They allow your custom objects to work with Python’s built-in functions and operators.

Common Mistakes with Methods
  • Forgetting parentheses: “hello”.upper returns the method object, not the result
  • Using a method that modifies in place and expecting it to return a value (.sort() returns None)
  • Calling a method that does not exist on that type (e.g., [1,2].upper())
  • Confusing methods with functions (len() is a function, not a method)
  • Using .append() with multiple arguments (it takes only one)
  • Forgetting that strings are immutable (methods return new strings, they do not change the original)
Check Your Understanding
  • What is the difference between a function and a method?
  • How do you call a method on an object?
  • What does “hello”.upper() return?
  • Why does my_list.sort() return None?
  • How can you find out what methods a string has?
  • What does it mean to chain methods?

⚡ Whisper

A method is a whisper attached to an object. The string says “make me louder” with .upper(). The list says “add this to me” with .append(). The dictionary says “show me your keys” with .keys(). Each object has its own voice. Its own set of whispers. Learn to listen. When you hold an object in your hands, pause and ask: what can you do? Then try the dot. Type the dot. Wait. Python will show you the methods. This is not memorization. This is conversation. The object tells you its capabilities. You just need to ask. And remember: methods with parentheses do something. Methods without parentheses are just references. The parentheses are the trigger. The action. The moment when the whisper becomes a spell.

Related posts