🕯️ 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.
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)
| Method | What It Does | Example |
|---|---|---|
| .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”]
| Method | What It Does | Example |
|---|---|---|
| .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]
| Method | What It Does | Example |
|---|---|---|
| .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 default | d.get(“b”, 0) → 0 |
| .pop(key) | Removes and returns value | d.pop(“a”) → 1 |
| .update(other) | Merges another dictionary | d.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}”)
| Method | What It Does | Example |
|---|---|---|
| .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
| Method | What It Does | Example | |
|---|---|---|---|
| .add(x) | Adds x to the set | s.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 (A | B) | 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
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)
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
| Operation | Function | Method | Why |
|---|---|---|---|
| Get length | len(obj) | obj.len() (no) | Function works on all types |
| Convert to string | str(obj) | obj.__str__() | Usually use str() function |
| Type check | type(obj) | obj.__class__ | Usually use type() function |
| String to upper | N/A | “hi”.upper() | Only strings have it |
| List append | N/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.
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.
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.
- 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)
- 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.