Python Methods
Python Methods
COMPLETE HANDBOOK
📘 PURPOSE 📘 PURPOSE
Converts every character in the string to UPPERCASE. Converts every character in the string to lowercase.
📝 SYNTAX 📝 SYNTAX
[Link]() [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
print("hello".upper()) print("PYTHON".lower())
✅ OUTPUT 1 ✅ OUTPUT 1
HELLO python
💻 EXAMPLE 2 💻 EXAMPLE 2
print("python 3".upper()) print("Hello World".lower())
✅ OUTPUT 2 ✅ OUTPUT 2
PYTHON 3 hello world
🐍 STRINGS capitalize() | title()
capitalize() title()
📘 PURPOSE 📘 PURPOSE
Makes the FIRST character uppercase and all others Capitalizes the first letter of EVERY word in the string.
lowercase.
📝 SYNTAX 📝 SYNTAX
[Link]() [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
print("hello world".capitalize()) print("hello world".title())
✅ OUTPUT 1 ✅ OUTPUT 1
Hello world Hello World
💻 EXAMPLE 2 💻 EXAMPLE 2
print("PYTHON".capitalize()) print("my name is ali".title())
✅ OUTPUT 2 ✅ OUTPUT 2
Python My Name Is Ali
🐍 STRINGS strip() | lstrip()
strip() lstrip()
📘 PURPOSE 📘 PURPOSE
Removes leading and trailing whitespace (or given Removes leading whitespace (or given chars) from the
characters). LEFT only.
📝 SYNTAX 📝 SYNTAX
[Link]() or [Link](chars) [Link]() or [Link](chars)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(" hello ".strip()) print(" hello ".lstrip())
✅ OUTPUT 1 ✅ OUTPUT 1
hello hello
💻 EXAMPLE 2 💻 EXAMPLE 2
print("--hi--".strip("-")) print("###hi".lstrip("#"))
✅ OUTPUT 2 ✅ OUTPUT 2
hi hi
🐍 STRINGS rstrip() | replace()
rstrip() replace()
📘 PURPOSE 📘 PURPOSE
Removes trailing whitespace (or given chars) from the Replaces all occurrences of a substring with another
RIGHT only. string.
📝 SYNTAX 📝 SYNTAX
[Link]() or [Link](chars) [Link](old, new, count=-1)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(" hello ".rstrip()) print("cat cat cat".replace("cat", "dog"))
✅ OUTPUT 1 ✅ OUTPUT 1
hello dog dog dog
💻 EXAMPLE 2 💻 EXAMPLE 2
print("hi!!!".rstrip("!")) print("cat cat cat".replace("cat", "dog", 1))
✅ OUTPUT 2 ✅ OUTPUT 2
hi dog cat cat
🐍 STRINGS split() | join()
split() join()
📘 PURPOSE 📘 PURPOSE
Splits the string into a list using a delimiter. Default is Joins elements of an iterable into a single string using
whitespace. a separator.
📝 SYNTAX 📝 SYNTAX
[Link](sep=None, maxsplit=-1) [Link](iterable)
💻 EXAMPLE 1 💻 EXAMPLE 1
print("a,b,c".split(",")) print(", ".join(["a","b","c"]))
✅ OUTPUT 1 ✅ OUTPUT 1
['a', 'b', 'c'] a, b, c
💻 EXAMPLE 2 💻 EXAMPLE 2
print("hello world".split()) print("-".join("ABC"))
✅ OUTPUT 2 ✅ OUTPUT 2
['hello', 'world'] A-B-C
🐍 STRINGS find() | index()
find() index()
📘 PURPOSE 📘 PURPOSE
Returns the index of the FIRST occurrence of a Like find(), but raises ValueError if the substring is not
substring. Returns -1 if not found. found.
📝 SYNTAX 📝 SYNTAX
[Link](sub, start=0, end=len(string)) [Link](sub, start=0, end=len(string))
💻 EXAMPLE 1 💻 EXAMPLE 1
print("hello".find("l")) print("hello".index("e"))
✅ OUTPUT 1 ✅ OUTPUT 1
2 1
💻 EXAMPLE 2 💻 EXAMPLE 2
print("hello".find("z")) print("hello".index("l"))
✅ OUTPUT 2 ✅ OUTPUT 2
-1 2
🐍 STRINGS count() | startswith()
count() startswith()
📘 PURPOSE 📘 PURPOSE
Returns the number of non-overlapping occurrences of Returns True if the string starts with the given prefix,
a substring. else False.
📝 SYNTAX 📝 SYNTAX
[Link](sub, start=0, end=len(string)) [Link](prefix, start=0, end=len(string))
💻 EXAMPLE 1 💻 EXAMPLE 1
print("banana".count("a")) print("python".startswith("py"))
✅ OUTPUT 1 ✅ OUTPUT 1
3 True
💻 EXAMPLE 2 💻 EXAMPLE 2
print("hello".count("l")) print("python".startswith("ja"))
✅ OUTPUT 2 ✅ OUTPUT 2
2 False
🐍 STRINGS endswith() | format()
endswith() format()
📘 PURPOSE 📘 PURPOSE
Returns True if the string ends with the given suffix, Inserts values into a string using {} placeholders.
else False.
📝 SYNTAX 📝 SYNTAX
[Link](suffix, start=0, end=len(string)) [Link](*args, **kwargs)
💻 EXAMPLE 1 💻 EXAMPLE 1
print("[Link]".endswith(".txt")) print("Hi {}!".format("Ali"))
✅ OUTPUT 1 ✅ OUTPUT 1
True Hi Ali!
💻 EXAMPLE 2 💻 EXAMPLE 2
print("[Link]".endswith(".jpg")) print("{name} is
{age}".format(name="Bob",age=25))
✅ OUTPUT 2 ✅ OUTPUT 2
False Bob is 25
🐍 STRINGS isdigit() | isalpha()
isdigit() isalpha()
📘 PURPOSE 📘 PURPOSE
Returns True if ALL characters in the string are digits Returns True if ALL characters are letters (no digits or
(0–9). spaces).
📝 SYNTAX 📝 SYNTAX
[Link]() [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
print("12345".isdigit()) print("Hello".isalpha())
✅ OUTPUT 1 ✅ OUTPUT 1
True True
💻 EXAMPLE 2 💻 EXAMPLE 2
print("12.3".isdigit()) print("Hello1".isalpha())
✅ OUTPUT 2 ✅ OUTPUT 2
False False
🐍 STRINGS zfill() | center()
zfill() center()
📘 PURPOSE 📘 PURPOSE
Pads the string with zeros on the LEFT to reach the Centers the string within a given width, padded with a
given width. fill character.
📝 SYNTAX 📝 SYNTAX
[Link](width) [Link](width, fillchar=' ')
💻 EXAMPLE 1 💻 EXAMPLE 1
print("42".zfill(5)) print("hi".center(10))
✅ OUTPUT 1 ✅ OUTPUT 1
00042 hi
💻 EXAMPLE 2 💻 EXAMPLE 2
print("101".zfill(6)) print("hi".center(10, "*"))
✅ OUTPUT 2 ✅ OUTPUT 2
000101 ****hi****
📋 LISTS
Dynamic arrays, sorting, and comprehensions
📋 LISTS append() | extend()
append() extend()
📘 PURPOSE 📘 PURPOSE
Adds a single element to the END of the list. Adds ALL elements from an iterable to the END of the
list.
📝 SYNTAX 📝 SYNTAX
[Link](element) [Link](iterable)
💻 EXAMPLE 1 💻 EXAMPLE 1
lst = [1,2,3] lst = [1,2]
[Link](4) [Link]([3,4])
print(lst) print(lst)
✅ OUTPUT 1 ✅ OUTPUT 1
[1, 2, 3, 4] [1, 2, 3, 4]
💻 EXAMPLE 2 💻 EXAMPLE 2
lst = ["a","b"] lst = [1,2]
[Link]("c") [Link]("ab")
print(lst) print(lst)
✅ OUTPUT 2 ✅ OUTPUT 2
['a', 'b', 'c'] [ 1, 2, 'a', 'b']
📋 LISTS insert() | remove()
insert() remove()
📘 PURPOSE 📘 PURPOSE
Inserts an element at a SPECIFIC index, shifting Removes the FIRST occurrence of the given value from
elements right. the list.
📝 SYNTAX 📝 SYNTAX
[Link](index, element) [Link](value)
💻 EXAMPLE 1 💻 EXAMPLE 1
lst = [1,2,3] lst = [1,2,3,2]
[Link](1, 99) [Link](2)
print(lst) print(lst)
✅ OUTPUT 1 ✅ OUTPUT 1
[1, 99, 2, 3] [1, 3, 2]
💻 EXAMPLE 2 💻 EXAMPLE 2
lst = [1,2,3] lst = ["a","b"]
[Link](0, 0) [Link]("a")
print(lst) print(lst)
✅ OUTPUT 2 ✅ OUTPUT 2
[0, 1, 2, 3] ['b']
📋 LISTS pop() | clear()
pop() clear()
📘 PURPOSE 📘 PURPOSE
Removes and RETURNS the element at the given index Removes ALL elements from the list, leaving it empty.
(default: last).
📝 SYNTAX 📝 SYNTAX
[Link](index=-1) [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
lst = [1,2,3] lst = [1,2,3]
print([Link]()) [Link]()
print(lst)
✅ OUTPUT 1 ✅ OUTPUT 1
3 (lst is now [1, 2]) []
💻 EXAMPLE 2 💻 EXAMPLE 2
lst = [1,2,3] lst = ["a","b"]
print([Link](0)) [Link]()
print(lst)
✅ OUTPUT 2 ✅ OUTPUT 2
1 (lst is now [2, 3]) []
📋 LISTS index() | count()
index() count()
📘 PURPOSE 📘 PURPOSE
Returns the index of the FIRST occurrence of a value in Returns how many times a value appears in the list.
the list.
📝 SYNTAX 📝 SYNTAX
[Link](value, start=0, end=len(list)) [Link](value)
💻 EXAMPLE 1 💻 EXAMPLE 1
lst = [10,20,30,20] lst = [1,2,2,3,2]
print([Link](20)) print([Link](2))
✅ OUTPUT 1 ✅ OUTPUT 1
1 3
💻 EXAMPLE 2 💻 EXAMPLE 2
lst = ["a","b","c"] lst = ["a","b","a"]
print([Link]("c")) print([Link]("a"))
✅ OUTPUT 2 ✅ OUTPUT 2
2 2
📋 LISTS sort() | reverse()
sort() reverse()
📘 PURPOSE 📘 PURPOSE
Sorts the list IN-PLACE in ascending order (or by key). Reverses the order of elements IN-PLACE.
📝 SYNTAX 📝 SYNTAX
[Link](key=None, reverse=False) [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
lst = [3,1,4,1,5] lst = [1,2,3,4]
[Link]() [Link]()
print(lst) print(lst)
✅ OUTPUT 1 ✅ OUTPUT 1
[1, 1, 3, 4, 5] [4, 3, 2, 1]
💻 EXAMPLE 2 💻 EXAMPLE 2
lst = [3,1,4] lst = ["a","b","c"]
[Link](reverse=True) [Link]()
print(lst) print(lst)
✅ OUTPUT 2 ✅ OUTPUT 2
[4, 3, 1] ['c', 'b', 'a']
📋 LISTS copy() | List Slicing
copy() List Slicing
📘 PURPOSE 📘 PURPOSE
Returns a SHALLOW copy of the list (new list, same Extracts a sub-list using start:stop:step notation.
element references).
📝 SYNTAX 📝 SYNTAX
[Link]() list[start:stop:step]
💻 EXAMPLE 1 💻 EXAMPLE 1
a = [1,2,3] lst = [0,1,2,3,4,5]
b = [Link]() print(lst[1:4])
[Link](4)
✅ OUTPUT 1
print(a) ✅ OUTPUT 1
[1, 2, 3] [1, 2, 3]
💻 EXAMPLE 2 💻 EXAMPLE 2
a = [1,2,3] lst = [0,1,2,3,4,5]
b = [Link]() print(lst[::2])
print(b)
✅ OUTPUT 2 ✅ OUTPUT 2
[1, 2, 3] [0, 2, 4]
📋 LISTS List Comprehension | len()
List Comprehension len()
📘 PURPOSE 📘 PURPOSE
Creates a new list by applying an expression to each Returns the total number of elements in the list.
item in an iterable.
📝 SYNTAX 📝 SYNTAX
[expression for item in iterable if condition] len(list)
💻 EXAMPLE 1 💻 EXAMPLE 1
squares = [x**2 for x in range(5)] print(len([1,2,3,4]))
print(squares)
✅ OUTPUT 1 ✅ OUTPUT 1
[0, 1, 4, 9, 16] 4
💻 EXAMPLE 2 💻 EXAMPLE 2
evens = [x for x in range(10) if x%2==0] print(len([]))
print(evens)
✅ OUTPUT 2 ✅ OUTPUT 2
[0, 2, 4, 6, 8] 0
📋 LISTS in operator | list()
in operator list()
📘 PURPOSE 📘 PURPOSE
Checks if a value EXISTS inside the list. Returns True or Creates a list from any iterable (string, tuple, range,
False. etc.).
📝 SYNTAX 📝 SYNTAX
value in list list(iterable)
💻 EXAMPLE 1 💻 EXAMPLE 1
lst = [1,2,3] print(list(range(5)))
print(2 in lst)
✅ OUTPUT 1 ✅ OUTPUT 1
True [0, 1, 2, 3, 4]
💻 EXAMPLE 2 💻 EXAMPLE 2
lst = [1,2,3] print(list("hello"))
print(5 in lst)
✅ OUTPUT 2 ✅ OUTPUT 2
False ['h', 'e', 'l', 'l', 'o']
📦 TUPLES
Immutable sequences and structured data
📦 TUPLES count() | index()
count() index()
📘 PURPOSE 📘 PURPOSE
Returns the number of times a value appears in the Returns the index of the FIRST occurrence of a value in
tuple. the tuple.
📝 SYNTAX 📝 SYNTAX
[Link](value) [Link](value, start=0, end=len(tuple))
💻 EXAMPLE 1 💻 EXAMPLE 1
t = (1, 2, 2, 3, 2) t = (10, 20, 30)
print([Link](2)) print([Link](20))
✅ OUTPUT 1 ✅ OUTPUT 1
3 1
💻 EXAMPLE 2 💻 EXAMPLE 2
t = ("a","b","a") t = ("a","b","c")
print([Link]("a")) print([Link]("c"))
✅ OUTPUT 2 ✅ OUTPUT 2
2 2
📦 TUPLES tuple() | Tuple Unpacking
tuple() Tuple Unpacking
📘 PURPOSE 📘 PURPOSE
Creates a tuple from any iterable (list, string, range, Assigns each element of a tuple to a separate variable
etc.). in one line.
📝 SYNTAX 📝 SYNTAX
tuple(iterable) a, b, c = tuple
💻 EXAMPLE 1 💻 EXAMPLE 1
print(tuple([1,2,3])) x, y, z = (10, 20, 30)
print(x, y, z)
✅ OUTPUT 1 ✅ OUTPUT 1
(1, 2, 3) 10 20 30
💻 EXAMPLE 2 💻 EXAMPLE 2
print(tuple("hello")) first, *rest = (1,2,3,4)
print(first, rest)
✅ OUTPUT 2 ✅ OUTPUT 2
('h','e','l','l','o') 1 [2, 3, 4]
📦 TUPLES len() / in | Tuple Slicing
len() / in Tuple Slicing
📘 PURPOSE 📘 PURPOSE
len() counts elements. The 'in' operator checks Extracts a portion of the tuple using index ranges.
membership.
📝 SYNTAX 📝 SYNTAX
len(tuple) | value in tuple tuple[start:stop:step]
💻 EXAMPLE 1 💻 EXAMPLE 1
t = (1,2,3,4,5) t = (0,1,2,3,4,5)
print(len(t)) print(t[1:4])
✅ OUTPUT 1 ✅ OUTPUT 1
5 (1, 2, 3)
💻 EXAMPLE 2 💻 EXAMPLE 2
t = (1,2,3) t = (0,1,2,3,4,5)
print(2 in t) print(t[::-1])
✅ OUTPUT 2 ✅ OUTPUT 2
True (5, 4, 3, 2, 1, 0)
📦 TUPLES Immutability | Named Tuple
Immutability Named Tuple
📘 PURPOSE 📘 PURPOSE
Tuples CANNOT be changed after creation — they are Creates a tuple with named fields for readable,
immutable. structured data.
📝 SYNTAX 📝 SYNTAX
t = (1, 2, 3) # elements are fixed from collections import namedtuple
Point = namedtuple('Point', ['x','y'])
💻 EXAMPLE 1 💻 EXAMPLE 1
t = (1,2,3) from collections import namedtuple
# t[0] = 99 ← raises TypeError P = namedtuple("P",["x","y"])
print(t[0]) p = P(3,4)
✅ OUTPUT 1 ✅ OUTPUT 1
print(p.x)
1 3
💻 EXAMPLE 2 💻 EXAMPLE 2
t = (1,2,3) p = P(3,4)
t = t + (4,) print(p)
print(t)
✅ OUTPUT 2 ✅ OUTPUT 2
(1, 2, 3, 4) P(x=3, y=4)
🔵 SETS
Unique collections and set operations
🔵 SETS add() | remove()
add() remove()
📘 PURPOSE 📘 PURPOSE
Adds a single element to the set. Ignored if already Removes a specific element. Raises KeyError if not
present. found.
📝 SYNTAX 📝 SYNTAX
[Link](element) [Link](element)
💻 EXAMPLE 1 💻 EXAMPLE 1
s = {1,2,3} s = {1,2,3}
[Link](4) [Link](2)
print(s) print(s)
✅ OUTPUT 1 ✅ OUTPUT 1
{1, 2, 3, 4} {1, 3}
💻 EXAMPLE 2 💻 EXAMPLE 2
s = {1,2,3} s = {1,2,3}
[Link](2) [Link](99) # raises KeyError
print(s)
✅ OUTPUT 2 ✅ OUTPUT 2
{1, 2, 3} # no duplicate KeyError: 99
🔵 SETS discard() | pop()
discard() pop()
📘 PURPOSE 📘 PURPOSE
Removes an element if it exists. Does NOTHING if not Removes and returns an ARBITRARY element. Raises
found (no error). KeyError if empty.
📝 SYNTAX 📝 SYNTAX
[Link](element) [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
s = {1,2,3} s = {1,2,3}
[Link](2) print([Link]())
print(s)
✅ OUTPUT 1 ✅ OUTPUT 1
{1, 3} 1 (any element — sets are unordered)
💻 EXAMPLE 2 💻 EXAMPLE 2
s = {1,2,3} s = {"a","b"}
[Link](99) print([Link]())
print(s)
✅ OUTPUT 2 ✅ OUTPUT 2
{1, 2, 3} # no error 'a' or 'b' (unpredictable)
🔵 SETS clear() | union()
clear() union()
📘 PURPOSE 📘 PURPOSE
Removes ALL elements from the set, leaving it empty. Returns a NEW set containing all elements from both
sets. Operator: |
📝 SYNTAX 📝 SYNTAX
[Link]() [Link](other) or set | other
💻 EXAMPLE 1 💻 EXAMPLE 1
s = {1,2,3} a = {1,2,3}
[Link]() b = {3,4,5}
print(s) print([Link](b))
✅ OUTPUT 1 ✅ OUTPUT 1
set() {1, 2, 3, 4, 5}
💻 EXAMPLE 2 💻 EXAMPLE 2
s = {"a","b"} print({1,2} | {2,3})
[Link]()
print(s)
✅ OUTPUT 2 ✅ OUTPUT 2
set() {1, 2, 3}
🔵 SETS intersection() | difference()
intersection() difference()
📘 PURPOSE 📘 PURPOSE
Returns a NEW set with elements common to BOTH Returns elements in the FIRST set but NOT in the
sets. Operator: & second. Operator: -
📝 SYNTAX 📝 SYNTAX
[Link](other) or set & other [Link](other) or set - other
💻 EXAMPLE 1 💻 EXAMPLE 1
a = {1,2,3} a = {1,2,3,4}
b = {2,3,4} b = {3,4,5}
print([Link](b)) print([Link](b))
✅ OUTPUT 1 ✅ OUTPUT 1
{2, 3} {1, 2}
💻 EXAMPLE 2 💻 EXAMPLE 2
print({1,2,3} & {3,4,5}) print({1,2,3} - {2,3})
✅ OUTPUT 2 ✅ OUTPUT 2
{3} {1}
🔵 SETS symmetric_difference() |
issubset()
symmetric_difference() issubset()
📘 PURPOSE 📘 PURPOSE
Returns elements in EITHER set but NOT in both. Returns True if ALL elements of this set are in the
Operator: ^ other set.
📝 SYNTAX 📝 SYNTAX
set.symmetric_difference(other) or set ^ other [Link](other) or set <= other
💻 EXAMPLE 1 💻 EXAMPLE 1
a = {1,2,3} print({1,2}.issubset({1,2,3}))
b = {3,4,5}
print(a^b)
✅ OUTPUT 1 ✅ OUTPUT 1
{1, 2, 4, 5} True
💻 EXAMPLE 2 💻 EXAMPLE 2
print({1,2} ^ {2,3}) print({1,5}.issubset({1,2,3}))
✅ OUTPUT 2 ✅ OUTPUT 2
{1, 3} False
🔵 SETS issuperset() | isdisjoint()
issuperset() isdisjoint()
📘 PURPOSE 📘 PURPOSE
Returns True if this set CONTAINS all elements of the Returns True if the two sets share NO common
other set. elements.
📝 SYNTAX 📝 SYNTAX
[Link](other) or set >= other [Link](other)
💻 EXAMPLE 1 💻 EXAMPLE 1
print({1,2,3}.issuperset({1,2})) print({1,2}.isdisjoint({3,4}))
✅ OUTPUT 1 ✅ OUTPUT 1
True True
💻 EXAMPLE 2 💻 EXAMPLE 2
print({1,2}.issuperset({1,2,3})) print({1,2}.isdisjoint({2,3}))
✅ OUTPUT 2 ✅ OUTPUT 2
False False
🔵 SETS update() | copy()
update() copy()
📘 PURPOSE 📘 PURPOSE
Adds ALL elements from an iterable INTO the set (in- Returns a SHALLOW copy of the set as a new set object.
place union).
📝 SYNTAX 📝 SYNTAX
[Link](iterable) [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
s = {1,2} a = {1,2,3}
[Link]([3,4]) b = [Link]()
print(s) [Link](4)
✅ OUTPUT 1 ✅ OUTPUT 1
print(a)
{1, 2, 3, 4} {1, 2, 3}
💻 EXAMPLE 2 💻 EXAMPLE 2
s = {1,2} a = {1,2,3}
[Link]({2,3}) b = [Link]()
print(s) print(b)
✅ OUTPUT 2 ✅ OUTPUT 2
{1, 2, 3} {1, 2, 3}
📖 DICTIONARIES
Key-value storage, lookups, and iteration
📖 DICTIONARIES get() | keys()
get() keys()
📘 PURPOSE 📘 PURPOSE
Returns the value for a key. Returns a default if key is Returns a view of all KEYS in the dictionary.
not found (no error).
📝 SYNTAX 📝 SYNTAX
[Link](key, default=None) [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
d = {"a":1,"b":2} d = {"a":1,"b":2}
print([Link]("a")) print([Link]())
✅ OUTPUT 1 ✅ OUTPUT 1
1 dict_keys(['a', 'b'])
💻 EXAMPLE 2 💻 EXAMPLE 2
d = {"a":1} d = {"x":10}
print([Link]("z", 0)) print(list([Link]()))
✅ OUTPUT 2 ✅ OUTPUT 2
0 ['x']
📖 DICTIONARIES values() | items()
values() items()
📘 PURPOSE 📘 PURPOSE
Returns a view of all VALUES in the dictionary. Returns a view of all (key, value) pairs as tuples.
📝 SYNTAX 📝 SYNTAX
[Link]() [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
d = {"a":1,"b":2} d = {"a":1,"b":2}
print([Link]()) print([Link]())
✅ OUTPUT 1 ✅ OUTPUT 1
dict_values([1, 2]) dict_items([('a',1),('b',2)])
💻 EXAMPLE 2 💻 EXAMPLE 2
d = {"x":10} for k,v in [Link](): print(k,v)
print(list([Link]()))
✅ OUTPUT 2 ✅ OUTPUT 2
[10] a1
b2
📖 DICTIONARIES update() | pop()
update() pop()
📘 PURPOSE 📘 PURPOSE
Updates the dictionary with key-value pairs from Removes the key and returns its value. Raises KeyError
another dict or iterable. if key missing.
📝 SYNTAX 📝 SYNTAX
[Link](other_dict) [Link](key, default=None)
💻 EXAMPLE 1 💻 EXAMPLE 1
d = {"a":1} d = {"a":1,"b":2}
[Link]({"b":2}) print([Link]("a"))
print(d)
✅ OUTPUT 1 ✅ OUTPUT 1
{'a': 1, 'b': 2} 1 (d is now {'b': 2})
💻 EXAMPLE 2 💻 EXAMPLE 2
d = {"a":1} d = {"a":1}
[Link]({"a":99}) print([Link]("z", 0))
print(d)
✅ OUTPUT 2 ✅ OUTPUT 2
{'a': 99} # overwrites 0 (no error with default)
📖 DICTIONARIES popitem() | clear()
popitem() clear()
📘 PURPOSE 📘 PURPOSE
Removes and returns the LAST inserted (key, value) Removes ALL key-value pairs from the dictionary,
pair as a tuple. leaving it empty.
📝 SYNTAX 📝 SYNTAX
[Link]() [Link]()
💻 EXAMPLE 1 💻 EXAMPLE 1
d = {"a":1,"b":2} d = {"a":1,"b":2}
print([Link]()) [Link]()
print(d)
✅ OUTPUT 1 ✅ OUTPUT 1
('b', 2) {}
💻 EXAMPLE 2 💻 EXAMPLE 2
d = {"x":10} d = {"x":10}
print([Link]()) [Link]()
print(d)
✅ OUTPUT 2 ✅ OUTPUT 2
('x', 10) {}
📖 DICTIONARIES copy() | setdefault()
copy() setdefault()
📘 PURPOSE 📘 PURPOSE
Returns a SHALLOW copy of the dictionary as a new Returns the value for a key. If key is missing, inserts it
dict object. with a default value.
📝 SYNTAX 📝 SYNTAX
[Link]() [Link](key, default=None)
💻 EXAMPLE 1 💻 EXAMPLE 1
d = {"a":1} d = {"a":1}
d2 = [Link]() print([Link]("a", 0))
d2["b"]=2
✅ OUTPUT 1
print(d) ✅ OUTPUT 1
{'a': 1} 1 (key exists, returns 1)
💻 EXAMPLE 2 💻 EXAMPLE 2
d = {"a":1} d = {"a":1}
d2 = [Link]() print([Link]("b", 99))
print(d2)
✅ OUTPUT 2 ✅ OUTPUT 2
{'a': 1} 99 (adds 'b':99 to d)
📖 DICTIONARIES fromkeys() | in operator
fromkeys() in operator
📘 PURPOSE 📘 PURPOSE
Creates a new dictionary from a sequence of keys with Checks if a KEY exists in the dictionary. Returns True
the same default value. or False.
📝 SYNTAX 📝 SYNTAX
[Link](keys, value=None) key in dict
💻 EXAMPLE 1 💻 EXAMPLE 1
print([Link](["a","b","c"], 0)) d = {"a":1,"b":2}
print("a" in d)
✅ OUTPUT 1 ✅ OUTPUT 1
{'a': 0, 'b': 0, 'c': 0} True
💻 EXAMPLE 2 💻 EXAMPLE 2
print([Link]("xyz")) d = {"a":1}
print(1 in d)
✅ OUTPUT 2 ✅ OUTPUT 2
{'x': None, 'y': None, 'z': None} False # checks keys, not values!
📖 DICTIONARIES Dict Comprehension | Merge |
operator
Dict Comprehension Merge | operator
📘 PURPOSE 📘 PURPOSE
Creates a new dictionary using an expression in a Merges two dicts into a NEW dict (Python 3.9+). Right
compact one-line syntax. side wins on conflict.
📝 SYNTAX 📝 SYNTAX
{key: value for item in iterable if condition} merged = dict1 | dict2
💻 EXAMPLE 1 💻 EXAMPLE 1
sq = {x: x**2 for x in range(5)} a = {"x":1}
print(sq) b = {"y":2}
print(a | b)
✅ OUTPUT 1 ✅ OUTPUT 1
{0:0, 1:1, 2:4, 3:9, 4:16} {'x': 1, 'y': 2}
💻 EXAMPLE 2 💻 EXAMPLE 2
d = {k: v*2 for k,v in {"a":1,"b":2}.items()} a = {"k":1}
print(d) b = {"k":9}
print(a | b)
✅ OUTPUT 2 ✅ OUTPUT 2
{'a':2, 'b':4} {'k': 9} # b wins
📖 DICTIONARIES len() | sorted()
len() sorted()
📘 PURPOSE 📘 PURPOSE
Returns the total number of key-value pairs in the Returns a sorted list of the dictionary's keys (does not
dictionary. modify the dict).
📝 SYNTAX 📝 SYNTAX
len(dict) sorted(dict) or sorted([Link]())
💻 EXAMPLE 1 💻 EXAMPLE 1
d = {"a":1,"b":2,"c":3} d = {"b":2,"a":1,"c":3}
print(len(d)) print(sorted(d))
✅ OUTPUT 1 ✅ OUTPUT 1
3 ['a', 'b', 'c']
💻 EXAMPLE 2 💻 EXAMPLE 2
print(len({})) d = {"b":2,"a":1}
print(sorted([Link]()))
✅ OUTPUT 2 ✅ OUTPUT 2
0 [1, 2]
🔢 NUMBERS
Type conversion, math, and numeric operations
🔢 NUMBERS int() | float()
int() float()
📘 PURPOSE 📘 PURPOSE
Converts a value to an integer. Truncates floats; parses Converts a value to a floating-point number.
numeric strings.
📝 SYNTAX 📝 SYNTAX
int(value, base=10) float(value)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(int(3.9)) print(float(5))
✅ OUTPUT 1 ✅ OUTPUT 1
3 (truncates, NOT rounds) 5.0
💻 EXAMPLE 2 💻 EXAMPLE 2
print(int("42")) print(float("3.14"))
✅ OUTPUT 2 ✅ OUTPUT 2
42 3.14
🔢 NUMBERS abs() | round()
abs() round()
📘 PURPOSE 📘 PURPOSE
Returns the absolute (positive) value of a number. Rounds a number to a given number of decimal places
(default 0).
📝 SYNTAX 📝 SYNTAX
abs(number) round(number, ndigits=0)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(abs(-42)) print(round(3.14159, 2))
✅ OUTPUT 1 ✅ OUTPUT 1
42 3.14
💻 EXAMPLE 2 💻 EXAMPLE 2
print(abs(-3.14)) print(round(2.5))
✅ OUTPUT 2 ✅ OUTPUT 2
3.14 2 (banker's rounding!)
🔢 NUMBERS pow() | divmod()
pow() divmod()
📘 PURPOSE 📘 PURPOSE
Returns x raised to the power y. With 3 args: (x**y) % z Returns both the quotient and remainder as a tuple in
efficiently. a single call.
📝 SYNTAX 📝 SYNTAX
pow(x, y) or pow(x, y, z) divmod(dividend, divisor)
💻 EXAMPLE 1 💻💻 EXAMPLE
EXAMPLE 2 1
print(pow(2, 10)) print(divmod(10, 3))5))
print(divmod(17,
✅ OUTPUT 1 ✅ OUTPUT 1
1024 (3, 2) # 17 = 5*3 + 2
💻 EXAMPLE 2
print(pow(2, 10, 100))
✅ OUTPUT 2 ✅ OUTPUT 2
24 ( 2**10 % 100 ) (3, 1) # 10 = 3*3 + 1
🔢 NUMBERS bin() | hex()
bin() hex()
📘 PURPOSE 📘 PURPOSE
Converts an integer to its binary string representation Converts an integer to its hexadecimal string
(prefixed '0b'). representation (prefixed '0x').
📝 SYNTAX 📝 SYNTAX
bin(integer) hex(integer)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(bin(10)) print(hex(255))
✅ OUTPUT 1 ✅ OUTPUT 1
0b1010 0xff
💻 EXAMPLE 2 💻 EXAMPLE 2
print(bin(255)) print(hex(16))
✅ OUTPUT 2 ✅ OUTPUT 2
0b11111111 0x10
🔢 NUMBERS oct() | bool()
oct() bool()
📘 PURPOSE 📘 PURPOSE
Converts an integer to its octal string representation Converts a value to Boolean True or False using
(prefixed '0o'). Python's truth rules.
📝 SYNTAX 📝 SYNTAX
oct(integer) bool(value)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(oct(8)) print(bool(0), bool(""), bool([]))
✅ OUTPUT 1 ✅ OUTPUT 1
0o10 False False False
💻 EXAMPLE 2 💻 EXAMPLE 2
print(oct(64)) print(bool(1), bool("hi"), bool([1]))
✅ OUTPUT 2 ✅ OUTPUT 2
0o100 True True True
⚡ BUILT-INS
Python's most powerful built-in functions
⚡ BUILT-INS print() | input()
print() input()
📘 PURPOSE 📘 PURPOSE
Outputs values to the console. Supports sep and end Reads a line of text from the user. Always returns a
customisation. STRING.
📝 SYNTAX 📝 SYNTAX
print(*values, sep=' ', end='\n', file=[Link]) input(prompt='')
💻 EXAMPLE 1 💻 EXAMPLE 1
print("Hello", "World", sep="-") name = input("Enter name: ")
print(name)
✅ OUTPUT 1 ✅ OUTPUT 1
Hello-World Enter name: Ali
Ali
💻 EXAMPLE 2 💻 EXAMPLE 2
print("Hi", end=" ") age = int(input("Age: "))
print("!") print(age+1)
✅ OUTPUT 2 ✅ OUTPUT 2
Hi ! Age: 20
21
⚡ BUILT-INS len() | type()
len() type()
📘 PURPOSE 📘 PURPOSE
Returns the number of items in an object (string, list, Returns the data type of any object.
dict, etc.).
📝 SYNTAX 📝 SYNTAX
len(object) type(object)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(len("hello")) print(type(42))
✅ OUTPUT 1 ✅ OUTPUT 1
5 <class 'int'>
💻 EXAMPLE 2 💻 EXAMPLE 2
print(len([1,2,3,4])) print(type("hi"))
✅ OUTPUT 2 ✅ OUTPUT 2
4 <class 'str'>
⚡ BUILT-INS range() | enumerate()
range() enumerate()
📘 PURPOSE 📘 PURPOSE
Generates a sequence of integers. Commonly used in Returns an iterator of (index, value) pairs from any
for-loops. iterable.
📝 SYNTAX 📝 SYNTAX
range(stop) or range(start, stop, step) enumerate(iterable, start=0)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(list(range(5))) for i,v in enumerate(["a","b","c"]):
print(i,v)
✅ OUTPUT 1 ✅ OUTPUT 1
[0, 1, 2, 3, 4] 0a
1b
💻 EXAMPLE 2 💻
2 cEXAMPLE 2
print(list(range(1, 10, 2))) list(enumerate("xy", 1))
✅ OUTPUT 2 ✅ OUTPUT 2
[1, 3, 5, 7, 9] [(1,'x'), (2,'y')]
⚡ BUILT-INS zip() | map()
zip() map()
📘 PURPOSE 📘 PURPOSE
Pairs up elements from two or more iterables into Applies a function to every element of an iterable.
tuples. Returns a map object.
📝 SYNTAX 📝 SYNTAX
zip(iterable1, iterable2, ...) map(function, iterable)
💻 EXAMPLE 1 💻 EXAMPLE 1
a=[1,2,3] print(list(map(str, [1,2,3])))
b=["a","b","c"]
print(list(zip(a,b)))
✅ OUTPUT 1 ✅ OUTPUT 1
[(1,'a'),(2,'b'),(3,'c')] ['1', '2', '3']
💻 EXAMPLE 2 💻 EXAMPLE 2
keys=["x","y"] print(list(map(lambda x: x**2, [1,2,3])))
vals=[10,20]
print(dict(zip(keys,vals)))
✅ OUTPUT 2 ✅ OUTPUT 2
{'x':10,'y':20} [1, 4, 9]
⚡ BUILT-INS filter() | sorted()
filter() sorted()
📘 PURPOSE 📘 PURPOSE
Filters elements from an iterable — keeps only those Returns a NEW sorted list from any iterable. Does not
where function returns True. modify the original.
📝 SYNTAX 📝 SYNTAX
filter(function, iterable) sorted(iterable, key=None, reverse=False)
💻 EXAMPLE 1 💻 EXAMPLE 1
evens = filter(lambda x: x%2==0, [1,2,3,4,5]) print(sorted([3,1,4,1,5]))
print(list(evens))
✅ OUTPUT 1 ✅ OUTPUT 1
[2, 4] [1, 1, 3, 4, 5]
💻 EXAMPLE 2 💻 EXAMPLE 2
filter(None, [0,"",1,"a"]) print(sorted(["banana","apple"], key=len))
# list it:
✅ OUTPUT 2 ✅ OUTPUT 2
[1, 'a'] # removes falsy values ['apple', 'banana']
⚡ BUILT-INS reversed() | sum()
reversed() sum()
📘 PURPOSE 📘 PURPOSE
Returns a reverse iterator over a sequence. Does NOT Returns the total sum of all elements in an iterable.
create a new list.
📝 SYNTAX 📝 SYNTAX
reversed(sequence) sum(iterable, start=0)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(list(reversed([1,2,3]))) print(sum([1,2,3,4,5]))
✅ OUTPUT 1 ✅ OUTPUT 1
[3, 2, 1] 15
💻 EXAMPLE 2 💻 EXAMPLE 2
print(list(reversed("abc"))) print(sum([1,2,3], 10))
✅ OUTPUT 2 ✅ OUTPUT 2
['c', 'b', 'a'] 16 (10 + 1+2+3)
⚡ BUILT-INS min() / max() | isinstance()
min() / max() isinstance()
📘 PURPOSE 📘 PURPOSE
min() returns the smallest item. max() returns the Checks if an object is an instance of a class or a tuple
largest. of classes.
📝 SYNTAX 📝 SYNTAX
min(iterable, key=None) | max(iterable, key=None) isinstance(object, classinfo)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(min([3,1,4,1,5])) print(isinstance(42, int))
✅ OUTPUT 1 ✅ OUTPUT 1
1 True
💻 EXAMPLE 2 💻 EXAMPLE 2
print(max("banana", key=len)) print(isinstance(3.14, (int,float)))
✅ OUTPUT 2 ✅ OUTPUT 2
banana (longest string) True
⚡ BUILT-INS open() | lambda
open() lambda
📘 PURPOSE 📘 PURPOSE
Opens a file and returns a file object for reading or Creates a small anonymous (inline) function in a single
writing. expression.
📝 SYNTAX 📝 SYNTAX
open(file, mode='r', encoding='utf-8') lambda arguments: expression
💻 EXAMPLE 1 💻 EXAMPLE 1
with open('[Link]','r') as f: double = lambda x: x * 2
print([Link]()) print(double(5))
✅ OUTPUT 1 ✅ OUTPUT 1
Contents of [Link] 10
💻 EXAMPLE 2 💻 EXAMPLE 2
with open('[Link]','w') as f: add = lambda x,y: x+y
[Link]('Hello') print(add(3,4))
✅ OUTPUT 2 ✅ OUTPUT 2
Writes 'Hello' to [Link] 7
⚡ BUILT-INS any() / all() | id()
any() / all() id()
📘 PURPOSE 📘 PURPOSE
any() → True if at least one item is truthy. all() → True Returns the unique memory identity (address) of an
if ALL are truthy. object.
📝 SYNTAX 📝 SYNTAX
any(iterable) | all(iterable) id(object)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(any([0, 0, 1, 0])) a = [1,2]
b=a
print(id(a)==id(b))
✅ OUTPUT 1 ✅ OUTPUT 1
True True (same object)
💻 EXAMPLE 2 💻 EXAMPLE 2
print(all([1, 2, 3])) a = [1,2]
b = [Link]()
print(id(a)==id(b))
✅ OUTPUT 2 ✅ OUTPUT 2
True False (different objects)
⚡ BUILT-INS dir() | help()
dir() help()
📘 PURPOSE 📘 PURPOSE
Returns a list of all attributes and methods of an Displays the built-in documentation for any function,
object. method, or object.
📝 SYNTAX 📝 SYNTAX
dir(object) help(object)
💻 EXAMPLE 1 💻 EXAMPLE 1
print(dir([])) help([Link])
✅ OUTPUT 1 ✅ OUTPUT 1
['append','clear','copy','count',...] (all list methods) Displays docstring: 'Return a copy of the string...'
💻 EXAMPLE 2 💻 EXAMPLE 2
print(dir("")) help([Link])
✅ OUTPUT 2 ✅ OUTPUT 2
['capitalize','center','count','encode',...] Displays docstring: 'Sort the list in ascending...'