Python-07
Built-In Functions in Python
Python comes with a lot of functionality inclued, so let's have a look what's available.
Python-07
Built-In Functions in Python
Python comes with a lot of functionality inclued, so let's have a look what's available.
Lesson Objectives
Lesson Objectives
What is a function ?
Built-In Functions in Python
How to use them?
Are you Ready?
Lesson Summary
Lesson Summary
Built-In Functions in Python
Here is a Table of all Built-In Functions in Python that are sorted so you know what you need to learn and what can be ignored completely.
Built-In Functions
All
✨Essential
Regular
📦OOP
🔹Basic
❌Ignore
✨
enumerate()
Adds counter to an iterable by pairing each element with its position index, creating a sequence of tuples.
# Materials list
materials = ["concrete", "steel", "glass", "wood", "brick"]
# Add Iteration Count with enumerate()
for n, material in enumerate(materials):
print(f"{n}. {material}")
# 0. concrete
# 1. steel
# 2. glass
# 3. wood
# 4. brick
✨
isinstance()
Checks if an object is an instance of a specified class or type.
x = 42
y = "hello"
z = [1, 2, 3]
print(isinstance(x, int)) # True
print(isinstance(y, str)) # True
print(isinstance(z, list)) # True
print(isinstance(x, float)) # False
# Check against multiple types
print(isinstance(x, (int, float))) # True - x is an int or float
# Check for subclasses
class Animal:
pass
class Dog(Animal):
pass
fido = Dog()
print(isinstance(fido, Dog)) # True
print(isinstance(fido, Animal)) # True - subclass relationship
✨
len()
Returns the number of items in an object.
# Length of a string (number of characters)
text = "hello world"
print(len(text)) # 11
# Length of a list (number of elements)
numbers = [10, 20, 30, 40, 50]
print(len(numbers)) # 5
# Length of a dictionary (number of key-value pairs)
person = {"name": "Erik",
"age": 29,
"city": "Vienna"}
print(len(person)) # 3
✨
open()
Creates a file object, allowing you to read from or write to files using different modes ('r' for read, 'w' for write, 'a' for append).
# Recommended way using 'with' context-manager for auto-closing file.
# Read
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Write
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# Basic file reading ( NOT RECOMMENDED as file might get corrupted is not closed.)
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
✨
print()
Outputs text to the console, with options to separate arguments and control line endings.
print("Hello World.")
✨
range()
generates a sequence of numbers with optional start, stop, and step parameters.
# Creating a range of numbers
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(2, 7))) # Output: [2, 3, 4, 5, 6]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]
# Often used in Loops
for n in range(10):
print(f'Attemprt # {n}')
✨
sorted()
Returns a new sorted list from the given iterable, with optional reverse sorting.
# Sorted - Numeric
numbers = [5, 2, 8, 1, 9]
print(sorted(numbers)) # Output: [1, 2, 5, 8, 9]
print(sorted(numbers, reverse=True)) # Output: [9, 8, 5, 2, 1]
# Sorted - Alphabetic
materials = ['Steel', 'Concrete', 'Wood', 'Brick']
print(sorted(materials)) # Output: ['Brick', 'Concrete', 'Steel', 'Wood']
# Sorting a dictionary by value without lambda or imports
materials = {'Steel': 120,
'Concrete': 75,
'Wood': 40,
'Brick': 95}
# Define a function to return the second element (value)
def get_value(item):
return item[1]
sorted_materials = sorted(materials.items(), key=get_value)
print(sorted_materials) # Output: [('Wood', 40), ('Concrete', 75), ('Brick', 95), ('Steel', 120)]
✨
type()
Returns the type of an object, helping identify its data type or class, often use for debugging and understanding variables.
print(type('Hello World')) # <class 'str'>
print(type(69)) # <class 'int'>
print(type([1,2,3])) # <class 'list'>
print(type(None)) # <class 'NoneType'>
✨
zip()
Creates an iterator of tuples by combining elements from multiple iterables, useful for pairing related architectural data.
materials = ['Concrete', 'Steel', 'Wood']
strengths = [25, 50, 15]
# Combining materials and their strengths
zip_materials = zip(materials, strengths) #<zip object at 0x7f59a148dcc0>
material_strengths = list(zip_materials)
print(material_strengths) # Output: [('Concrete', 25), ('Steel', 50), ('Wood', 15)]
Built-In Functions
All
✨Essential
Regular
📦OOP
🔹Basic
❌Ignore
abs()
Return the absolute value of a number. The argument may be an integer, a floating-point number
print(abs(10)) #10
print(abs(-10)) #10
all()
Return True if all elements of the iterable are true
print(all([True, 1, "non-empty"])) # Output: True
print(all([True, 0, "non-empty"])) # Output: False
print(all([1>0, 5>2])) # Output: True
any()
The any() function returns True if at least one item in an iterable (list, tuple, dictionary, etc.) evaluates to True.
levels = [False, True, False]
print(any(levels)) # True
zeros = [0, 0, 0]
print(any(zeros)) # False (zero represents False)
nums = [-10, -5]
print(any(nums)) # True (negative numbers provide True)
view_templates = [None, "Architectural Plan", None]
print(any(view_templates)) # True
🔹
bool()
Converts value to a Boolean (True or False). Generally, any non-zero or non-empty value returns True; 0, None, or empty values return False.
elements = [] # Empty List
views = ['View_A', 'View_B', 'View_C']
text = 'Text'
num = 5
zero = 0
print(bool(elements)) # False
print(bool(views)) # True
print(bool(text)) # True
print(bool(num)) # True
print(bool(zero)) # False
num_floors = 0
has_floors = bool(num_floors) # Will be False, because num_floors is 0
print("Building has floors?", has_floors)
📦
classmethod()
This decorator creates a method that operates on the class rather than an instance.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@classmethod
def from_square(cls, side_length):
return cls(side_length, side_length)
# Create a rectangle from a square
square_rect = Rectangle.from_square(5)
print(f"Width: {square_rect.width}, Height: {square_rect.height}") # Width: 5, Height: 5
📦
delattr()
Deletes an attribute from an object.
class Person:
def __init__(self):
self.name = "Erik"
self.age = 29
self.temp = "temporary data"
# Create a person
p = Person()
print(vars(p)) # {'name': 'Alice', 'age': 30, 'temp': 'temporary data'}
# Delete the temp attribute
delattr(p, "temp")
print(vars(p)) # {'name': 'Alice', 'age': 30}
# Alternative syntax
del p.age
print(vars(p)) # {'name': 'Alice'}
🔹
dict()
Function to create a dictionary (a collection of key-value pairs)
#Empty dictionary
empty_dict = dict()
print(empty_dict) # {}
# From key-value pairs
person = dict(name="Erik", age=29, city="Vienna")
print(person) # {'name': 'Erik', 'age': 29, 'city': 'Vienna'}
# From a list of tuples
items = [("name", "Erik"), ("age", 29), ("city", "Vienna")]
person = dict(items)
print(person) # {'name': 'Erik', 'age': 29, 'city': 'Vienna'}
dir()
Returns a list of attributes and methods of an object, helping you explore its properties and capabilities. Used for debugging to understand objects, classes and modules.
print(dir(str)) # ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(list)) # ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
print(dir(dict)) # ['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
# 💡 Keep in mind that attributes with underscores __ represents internal attributes that shouldn't be used directly.
# As a beginner ignore them.
# Make it easier to read with For-Loop
for i in dir(list):
print(i)
divmod()
Takes two numbers and returns a tuple containing their quotient and remainder.
# Basic division and remainder
result = divmod(13, 5)
print(result) # (2, 3) - quotient is 2, remainder is 3
✨
enumerate()
Adds counter to an iterable by pairing each element with its position index, creating a sequence of tuples.
# Materials list
materials = ["concrete", "steel", "glass", "wood", "brick"]
# Add Iteration Count with enumerate()
for n, material in enumerate(materials):
print(f"{n}. {material}")
# 0. concrete
# 1. steel
# 2. glass
# 3. wood
# 4. brick
filter()
Creates an iterator containing only the elements from an iterable for which a function returns True.
# Define a function that checks if a number is even
def is_even(number):
return number % 2 == 0
# Filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers) # Returns <filter object at 0x7bf6e28b9690>
print(list(even_numbers)) # [2, 4, 6, 8, 10]
# Alternative using List Comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
🔹
float()
Converts a number or string to a floating-point number.
# Integer to float
print(float(10)) # 10.0
# String to float
print(float("3.14")) # 3.14
# Scientific notation
print(float("1e3")) # 1000.0
format()
Formats a single value according to a format specification and returns a formatted string.
# Basic formatting
print(format(123, "d")) # '123' (integer)
print(format(123.456, "f")) # '123.456000' (float)
print(format(123.456, ".2f")) # '123.46' (float with 2 decimal places)
# Width and alignment
print(format("center", "^10")) # ' center ' (centered in 10 spaces)
print(format("left", "<10")) # 'left ' (left-aligned in 10 spaces)
print(format("right", ">10")) # ' right' (right-aligned in 10 spaces)
# Numbers with thousands separator
print(format(1234567, ",d")) # '1,234,567'
# Percentage
print(format(0.25, ".0%")) # '25%'
🔹
frozenset()
Creates an immutable version of a set - a collection that cannot be changed after creation.
# Create a frozenset from a list with duplicates
materials = ["concrete", "wood", "steel", "glass", "wood", "concrete", "brick"]
building_materials = frozenset(materials)
print(building_materials)
# frozenset({'glass', 'steel', 'wood', 'concrete', 'brick'})
# Notice duplicates are automatically removed
# 💡 Can be ignored as rarely used by anyone.
📦
getattr()
Retrieves the value of a named attribute(property/method) from an object.
# Define Class Example
class Building:
def __init__(self):
self.height = 100
self.width = 50
def calculate_area(self):
return self.height * self.width
# Create a building object
building = Building()
#💡 Get attribute values using getattr()
height = getattr(building, "height")
print(height) # 100
#💡 Get a method and call it
area_method = getattr(building, "calculate_area")
print(area_method()) # 5000
#💡 Provide a default value for non-existent attributes
color = getattr(building, "color", "No color specified")
print(color) # "No color specified"
📦
hasattr()
Checks if an object has a specified attribute.
class Building:
def __init__(self):
self.height = 100
self.width = 50
def calculate_area(self):
return self.height * self.width
# Create a building object
building = Building()
# Check if attributes exist
print(hasattr(building, "height")) # True
print(hasattr(building, "color")) # False
print(hasattr(building, "calculate_area")) # True
# Useful in conditional statements
if hasattr(building, "width"):
print(f"Width: {building.width}")
else:
print("No width attribute found")
help()
Invokes the built-in Python help system.
# Get help on a built-in function
help(print)
# Get help on a type/class
help(str)
# Get help on a method
help(str.format)
# Get help on a module (needs to be imported first)
import math
help(math)
input()
Get user input as a string from the terminal.
# Basic input
name = input("What is your name? ")
print(f"Hello, {name}!")
# Input with conversion to a number
age_str = input("How old are you? ")
age = int(age_str)
print(f"Next year, you'll be {age + 1}")
🔹
int()
Converts a value to an integer.
# Convert string to integer
print(int("42")) # 42
# Convert float to integer (truncates decimal part)
print(int(3.99)) # 3
print(int(-3.99)) # -3
✨
isinstance()
Checks if an object is an instance of a specified class or type.
x = 42
y = "hello"
z = [1, 2, 3]
print(isinstance(x, int)) # True
print(isinstance(y, str)) # True
print(isinstance(z, list)) # True
print(isinstance(x, float)) # False
# Check against multiple types
print(isinstance(x, (int, float))) # True - x is an int or float
# Check for subclasses
class Animal:
pass
class Dog(Animal):
pass
fido = Dog()
print(isinstance(fido, Dog)) # True
print(isinstance(fido, Animal)) # True - subclass relationship
📦
issubclass()
Checks if a class is a subclass of another class.
# Define some classes
class Animal:
pass
class Mammal(Animal):
pass
class Dog(Mammal):
pass
class Fish(Animal):
pass
# Check subclass relationships
print(issubclass(Mammal, Animal)) # True
print(issubclass(Dog, Mammal)) # True
print(issubclass(Dog, Animal)) # True - indirect subclass
print(issubclass(Fish, Mammal)) # False
print(issubclass(Animal, Animal)) # True - a class is a subclass of itself
# Check with multiple classes
print(issubclass(Dog, (Fish, Mammal))) # True - Dog is a subclass of Mammal
✨
len()
Returns the number of items in an object.
# Length of a string (number of characters)
text = "hello world"
print(len(text)) # 11
# Length of a list (number of elements)
numbers = [10, 20, 30, 40, 50]
print(len(numbers)) # 5
# Length of a dictionary (number of key-value pairs)
person = {"name": "Erik",
"age": 29,
"city": "Vienna"}
print(len(person)) # 3
🔹
list()
Creates a list object from an iterable or creates an empty list.
# Create an empty list
empty = list()
print(empty) # []
# Convert a string to a list of characters
text = "hello"
char_list = list(text)
print(char_list) # ['h', 'e', 'l', 'l', 'o']
# Convert a tuple to a list
data = (1, 2, 3)
data_list = list(data)
print(data_list) # [1, 2, 3]
# Convert a set to a list
unique = {3, 1, 4, 1, 5} # Duplicates removed by set
print(list(unique)) # [3, 1, 4, 5] (order may vary)
# Convert a dictionary to a list of its keys
person = {"name": "Erik", "age": 29}
keys = list(person)
print(keys) # ['name', 'age']
map()
Applies a function to each item in an iterable and returns an iterator.
# Double each number in a list
def double(x):
return x * 2
numbers = [1, 2, 3, 4, 5]
doubled = map(double, numbers)
print(list(doubled)) # [2, 4, 6, 8, 10]
# Convert strings to integers
str_nums = ["10", "20", "30", "40"]
int_nums = map(int, str_nums)
print(list(int_nums)) # [10, 20, 30, 40]
# Multiple iterables with a function that takes multiple arguments
def add(x, y):
return x + y
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sums = map(add, list1, list2)
print(list(sums)) # [5, 7, 9]
# Alternative using list comprehension (often preferred)
numbers = [1, 2, 3, 4, 5]
doubled_comp = [x * 2 for x in numbers]
print(doubled_comp) # [2, 4, 6, 8, 10]
int_nums_comp = [int(x) for x in str_nums]
print(int_nums_comp) # [10, 20, 30, 40]
max()
Returns the largest item in an iterable or the largest of multiple arguments.
# Find tallest building height
heights = [381, 828, 508, 632]
print(max(heights)) # 828
# Find room with largest area
rooms = {"living": 24, "bedroom": 15, "kitchen": 16}
largest = max(rooms, key=rooms.get)
print(largest) # "living"
# Find building with maximum height
buildings = [
{"name": "Empire State", "height": 381},
{"name": "Burj Khalifa", "height": 828},
{"name": "Taipei 101", "height": 508}
]
def get_height(building):
return building["height"]
tallest = max(buildings, key=get_height)
print(tallest["name"]) # "Burj Khalifa"
min()
Returns the smallest item in an iterable or the smallest of multiple arguments.
# Find shortest building height
heights = [381, 828, 508, 632]
print(min(heights)) # 381
# Find room with smallest area
rooms = {"living": 24, "bedroom": 15, "kitchen": 16}
smallest = min(rooms, key=rooms.get)
print(smallest) # "bedroom"
# Find building with minimum height
buildings = [
{"name": "Empire State", "height": 381},
{"name": "Burj Khalifa", "height": 828},
{"name": "Taipei 101", "height": 508}
]
def get_height(building):
return building["height"]
shortest = min(buildings, key=get_height)
print(shortest["name"]) # "Empire State"
📦
object()
Creates a simple, base-level Python object with no custom properties or methods. Like a placeholder.
# object() creates a basic object with no attributes
x = object()
y = object()
print(x) # Prints unique object representation
print(type(x)) # Prints <class 'object'>
✨
open()
Creates a file object, allowing you to read from or write to files using different modes ('r' for read, 'w' for write, 'a' for append).
# Recommended way using 'with' context-manager for auto-closing file.
# Read
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Write
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# Basic file reading ( NOT RECOMMENDED as file might get corrupted is not closed.)
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
pow()
Raises a number to a specified power, with an optional third argument for modulo calculation.
print(pow(2, 3)) # Output: 8 (2 to the power of 3)
print(pow(2, 3, 5)) # Output: 3 (2^3 modulo 5)
# Alternative
print(2 ** 3) # Output: 8 (same as pow(2, 3))
✨
print()
Outputs text to the console, with options to separate arguments and control line endings.
print("Hello World.")
📦
property()
Decorator that converts method into a property based on its returned value.
class Building:
def __init__(self, name, height_ft):
self.name = name
self.height_ft = height_ft
@property
def height_m(self):
return self.height_ft * 0.3048
skyscraper = Building("EF-Tower", 455)
print(skyscraper.height_m) # Output: 138.684
# 💡 Best for creating properties that require calculation or multiple checks
✨
range()
generates a sequence of numbers with optional start, stop, and step parameters.
# Creating a range of numbers
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(2, 7))) # Output: [2, 3, 4, 5, 6]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]
# Often used in Loops
for n in range(10):
print(f'Attemprt # {n}')
📦
repr()
Rturns a dev string representation of an object, often used for debugging and development.
class Building:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Building(name='{self.name}')"
def __str__(self):
return f"{self.name} Building"
skyscraper = Building("EF-Tower")
print(repr(skyscraper)) # Output: Building(name='EF-Tower')
print(str(skyscraper)) # Output: EF-Tower Building
print(skyscraper) # Output: EF-Tower Building
reversed()
Reverse the order of items in sequences like lists, tuples and strings .
levels = ["Level 1", "Level 2", "Level 3"]
for level in reversed(levels):
print(level)
# Output:
# Level 3
# Level 2
# Level 1
round()
Return number rounded to X precision after the decimal point. If X is not provided returns the nearest integer to its input.
x = 12.3456776
y = 98.76543
z = 0.1234522222
print(x, y, z)
# Rounded Values
x_ = round(x, 1)
y_ = round(y, 1)
z_ = round(z, 1)
print(x_, y_, z_)
🔹
set()
Convert data into a set. Creates a collection of unique, unordered elements, removing duplicates automatically.
cats = ["Wall", "Door", "Wall", "Floor", "Door"]
unique_cats = set(cats)
print(unique_categories) # Output: {'Wall', 'Door', 'Floor'}
📦
setattr()
Assigns the value to the attribute, provided the object allows it
class Building:
def __init__(self, name):
self.name = name
skyscraper = Building("EF-Tower")
setattr(skyscraper, 'height', 69)
setattr(skyscraper, 'location', 'Tallinn, Estonia')
print(skyscraper.height) # Output: 69
print(skyscraper.location) # Output: Tallinn, Estonia
✨
sorted()
Returns a new sorted list from the given iterable, with optional reverse sorting.
# Sorted - Numeric
numbers = [5, 2, 8, 1, 9]
print(sorted(numbers)) # Output: [1, 2, 5, 8, 9]
print(sorted(numbers, reverse=True)) # Output: [9, 8, 5, 2, 1]
# Sorted - Alphabetic
materials = ['Steel', 'Concrete', 'Wood', 'Brick']
print(sorted(materials)) # Output: ['Brick', 'Concrete', 'Steel', 'Wood']
# Sorting a dictionary by value without lambda or imports
materials = {'Steel': 120,
'Concrete': 75,
'Wood': 40,
'Brick': 95}
# Define a function to return the second element (value)
def get_value(item):
return item[1]
sorted_materials = sorted(materials.items(), key=get_value)
print(sorted_materials) # Output: [('Wood', 40), ('Concrete', 75), ('Brick', 95), ('Steel', 120)]
📦
staticmethod()
Decorator that creates a method that belongs to a class rather than an instance, allowing access without creating an object.
class Converter:
@staticmethod
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
@staticmethod
def days_to_hours(days):
return days * 24
@staticmethod
def kilometers_to_miles(km):
return km * 0.621371
# Using the static methods
print(Converter.fahrenheit_to_celsius(32)) # Output: 0.0
print(Converter.days_to_hours(2)) # Output: 48
print(Converter.kilometers_to_miles(10)) # Output: 6.21371
🔹
str()
Converts an object to its string representation, using the object's __str__() method if defined.
print(str(123)) # Output: '123'
print(str(3.14)) # Output: '3.14'
print(str([1, 2, 3])) # Output: '[1, 2, 3]'
# OOP __str__ representation of objects
class Building:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Building: {self.name}"
skyscraper = Building("Empire State")
print(str(skyscraper)) # Output: Building: Empire State
sum()
Adds all numbers in an iterable, with an optional start value that defaults to zero.
# Summing numbers in a list
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
📦
super()
Function allows calling methods from a parent class, typically used in inheritance to extend or modify inherited behavior.
class Wall:
def __init__(self, height, width, material):
self.height = height
self.width = width
self.material = material
def area(self):
return self.height * self.width
class BrickWall(Wall):
def __init__(self, height, width, brick_type):
super().__init__(height, width, "Brick") # Call __init__ from parent Wall Class
self.brick_type = brick_type
def describe(self):
return f"{self.brick_type} brick wall, {self.height}x{self.width}"
kitchen_wall = BrickWall(3, 4, "Red Clay")
print(kitchen_wall.material) # Output: Brick
print(kitchen_wall.brick_type) # Output: Red Clay
print(kitchen_wall.describe()) # Output: Red Clay brick wall, 3x4
🔹
tuple()
Converts an iterable into a tuple, creating an immutable sequence of elements.
# Creating tuples from different iterables
print(tuple([1, 2, 3])) # Output: (1, 2, 3)
print(tuple('hello')) # Output: ('h', 'e', 'l', 'l', 'o')
# Empty tuple
empty = tuple()
print(empty) # Output: ()
✨
type()
Returns the type of an object, helping identify its data type or class, often use for debugging and understanding variables.
print(type('Hello World')) # <class 'str'>
print(type(69)) # <class 'int'>
print(type([1,2,3])) # <class 'list'>
print(type(None)) # <class 'NoneType'>
📦
vars()
Returns the __dict__ attribute of an object, which contains its instance variables.
class Building:
def __init__(self, name, height):
self.name = name
self.height = height
skyscraper = Building("EF-Tower", 69)
print(vars(skyscraper)) # Output: {'name': '"EF-Tower', 'height': 69}
✨
zip()
Creates an iterator of tuples by combining elements from multiple iterables, useful for pairing related architectural data.
materials = ['Concrete', 'Steel', 'Wood']
strengths = [25, 50, 15]
# Combining materials and their strengths
zip_materials = zip(materials, strengths) #<zip object at 0x7f59a148dcc0>
material_strengths = list(zip_materials)
print(material_strengths) # Output: [('Concrete', 25), ('Steel', 50), ('Wood', 15)]
Built-In Functions
All
✨Essential
Regular
📦OOP
🔹Basic
❌Ignore
abs()
Return the absolute value of a number. The argument may be an integer, a floating-point number
print(abs(10)) #10
print(abs(-10)) #10
all()
Return True if all elements of the iterable are true
print(all([True, 1, "non-empty"])) # Output: True
print(all([True, 0, "non-empty"])) # Output: False
print(all([1>0, 5>2])) # Output: True
any()
The any() function returns True if at least one item in an iterable (list, tuple, dictionary, etc.) evaluates to True.
levels = [False, True, False]
print(any(levels)) # True
zeros = [0, 0, 0]
print(any(zeros)) # False (zero represents False)
nums = [-10, -5]
print(any(nums)) # True (negative numbers provide True)
view_templates = [None, "Architectural Plan", None]
print(any(view_templates)) # True
🔹
bool()
Converts value to a Boolean (True or False). Generally, any non-zero or non-empty value returns True; 0, None, or empty values return False.
elements = [] # Empty List
views = ['View_A', 'View_B', 'View_C']
text = 'Text'
num = 5
zero = 0
print(bool(elements)) # False
print(bool(views)) # True
print(bool(text)) # True
print(bool(num)) # True
print(bool(zero)) # False
num_floors = 0
has_floors = bool(num_floors) # Will be False, because num_floors is 0
print("Building has floors?", has_floors)
📦
classmethod()
This decorator creates a method that operates on the class rather than an instance.
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
@classmethod
def from_square(cls, side_length):
return cls(side_length, side_length)
# Create a rectangle from a square
square_rect = Rectangle.from_square(5)
print(f"Width: {square_rect.width}, Height: {square_rect.height}") # Width: 5, Height: 5
📦
delattr()
Deletes an attribute from an object.
class Person:
def __init__(self):
self.name = "Erik"
self.age = 29
self.temp = "temporary data"
# Create a person
p = Person()
print(vars(p)) # {'name': 'Alice', 'age': 30, 'temp': 'temporary data'}
# Delete the temp attribute
delattr(p, "temp")
print(vars(p)) # {'name': 'Alice', 'age': 30}
# Alternative syntax
del p.age
print(vars(p)) # {'name': 'Alice'}
🔹
dict()
Function to create a dictionary (a collection of key-value pairs)
#Empty dictionary
empty_dict = dict()
print(empty_dict) # {}
# From key-value pairs
person = dict(name="Erik", age=29, city="Vienna")
print(person) # {'name': 'Erik', 'age': 29, 'city': 'Vienna'}
# From a list of tuples
items = [("name", "Erik"), ("age", 29), ("city", "Vienna")]
person = dict(items)
print(person) # {'name': 'Erik', 'age': 29, 'city': 'Vienna'}
dir()
Returns a list of attributes and methods of an object, helping you explore its properties and capabilities. Used for debugging to understand objects, classes and modules.
print(dir(str)) # ['capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
print(dir(list)) # ['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
print(dir(dict)) # ['clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
# 💡 Keep in mind that attributes with underscores __ represents internal attributes that shouldn't be used directly.
# As a beginner ignore them.
# Make it easier to read with For-Loop
for i in dir(list):
print(i)
divmod()
Takes two numbers and returns a tuple containing their quotient and remainder.
# Basic division and remainder
result = divmod(13, 5)
print(result) # (2, 3) - quotient is 2, remainder is 3
✨
enumerate()
Adds counter to an iterable by pairing each element with its position index, creating a sequence of tuples.
# Materials list
materials = ["concrete", "steel", "glass", "wood", "brick"]
# Add Iteration Count with enumerate()
for n, material in enumerate(materials):
print(f"{n}. {material}")
# 0. concrete
# 1. steel
# 2. glass
# 3. wood
# 4. brick
filter()
Creates an iterator containing only the elements from an iterable for which a function returns True.
# Define a function that checks if a number is even
def is_even(number):
return number % 2 == 0
# Filter even numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = filter(is_even, numbers) # Returns <filter object at 0x7bf6e28b9690>
print(list(even_numbers)) # [2, 4, 6, 8, 10]
# Alternative using List Comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in numbers if num % 2 == 0]
🔹
float()
Converts a number or string to a floating-point number.
# Integer to float
print(float(10)) # 10.0
# String to float
print(float("3.14")) # 3.14
# Scientific notation
print(float("1e3")) # 1000.0
format()
Formats a single value according to a format specification and returns a formatted string.
# Basic formatting
print(format(123, "d")) # '123' (integer)
print(format(123.456, "f")) # '123.456000' (float)
print(format(123.456, ".2f")) # '123.46' (float with 2 decimal places)
# Width and alignment
print(format("center", "^10")) # ' center ' (centered in 10 spaces)
print(format("left", "<10")) # 'left ' (left-aligned in 10 spaces)
print(format("right", ">10")) # ' right' (right-aligned in 10 spaces)
# Numbers with thousands separator
print(format(1234567, ",d")) # '1,234,567'
# Percentage
print(format(0.25, ".0%")) # '25%'
🔹
frozenset()
Creates an immutable version of a set - a collection that cannot be changed after creation.
# Create a frozenset from a list with duplicates
materials = ["concrete", "wood", "steel", "glass", "wood", "concrete", "brick"]
building_materials = frozenset(materials)
print(building_materials)
# frozenset({'glass', 'steel', 'wood', 'concrete', 'brick'})
# Notice duplicates are automatically removed
# 💡 Can be ignored as rarely used by anyone.
📦
getattr()
Retrieves the value of a named attribute(property/method) from an object.
# Define Class Example
class Building:
def __init__(self):
self.height = 100
self.width = 50
def calculate_area(self):
return self.height * self.width
# Create a building object
building = Building()
#💡 Get attribute values using getattr()
height = getattr(building, "height")
print(height) # 100
#💡 Get a method and call it
area_method = getattr(building, "calculate_area")
print(area_method()) # 5000
#💡 Provide a default value for non-existent attributes
color = getattr(building, "color", "No color specified")
print(color) # "No color specified"
📦
hasattr()
Checks if an object has a specified attribute.
class Building:
def __init__(self):
self.height = 100
self.width = 50
def calculate_area(self):
return self.height * self.width
# Create a building object
building = Building()
# Check if attributes exist
print(hasattr(building, "height")) # True
print(hasattr(building, "color")) # False
print(hasattr(building, "calculate_area")) # True
# Useful in conditional statements
if hasattr(building, "width"):
print(f"Width: {building.width}")
else:
print("No width attribute found")
help()
Invokes the built-in Python help system.
# Get help on a built-in function
help(print)
# Get help on a type/class
help(str)
# Get help on a method
help(str.format)
# Get help on a module (needs to be imported first)
import math
help(math)
input()
Get user input as a string from the terminal.
# Basic input
name = input("What is your name? ")
print(f"Hello, {name}!")
# Input with conversion to a number
age_str = input("How old are you? ")
age = int(age_str)
print(f"Next year, you'll be {age + 1}")
🔹
int()
Converts a value to an integer.
# Convert string to integer
print(int("42")) # 42
# Convert float to integer (truncates decimal part)
print(int(3.99)) # 3
print(int(-3.99)) # -3
✨
isinstance()
Checks if an object is an instance of a specified class or type.
x = 42
y = "hello"
z = [1, 2, 3]
print(isinstance(x, int)) # True
print(isinstance(y, str)) # True
print(isinstance(z, list)) # True
print(isinstance(x, float)) # False
# Check against multiple types
print(isinstance(x, (int, float))) # True - x is an int or float
# Check for subclasses
class Animal:
pass
class Dog(Animal):
pass
fido = Dog()
print(isinstance(fido, Dog)) # True
print(isinstance(fido, Animal)) # True - subclass relationship
📦
issubclass()
Checks if a class is a subclass of another class.
# Define some classes
class Animal:
pass
class Mammal(Animal):
pass
class Dog(Mammal):
pass
class Fish(Animal):
pass
# Check subclass relationships
print(issubclass(Mammal, Animal)) # True
print(issubclass(Dog, Mammal)) # True
print(issubclass(Dog, Animal)) # True - indirect subclass
print(issubclass(Fish, Mammal)) # False
print(issubclass(Animal, Animal)) # True - a class is a subclass of itself
# Check with multiple classes
print(issubclass(Dog, (Fish, Mammal))) # True - Dog is a subclass of Mammal
✨
len()
Returns the number of items in an object.
# Length of a string (number of characters)
text = "hello world"
print(len(text)) # 11
# Length of a list (number of elements)
numbers = [10, 20, 30, 40, 50]
print(len(numbers)) # 5
# Length of a dictionary (number of key-value pairs)
person = {"name": "Erik",
"age": 29,
"city": "Vienna"}
print(len(person)) # 3
🔹
list()
Creates a list object from an iterable or creates an empty list.
# Create an empty list
empty = list()
print(empty) # []
# Convert a string to a list of characters
text = "hello"
char_list = list(text)
print(char_list) # ['h', 'e', 'l', 'l', 'o']
# Convert a tuple to a list
data = (1, 2, 3)
data_list = list(data)
print(data_list) # [1, 2, 3]
# Convert a set to a list
unique = {3, 1, 4, 1, 5} # Duplicates removed by set
print(list(unique)) # [3, 1, 4, 5] (order may vary)
# Convert a dictionary to a list of its keys
person = {"name": "Erik", "age": 29}
keys = list(person)
print(keys) # ['name', 'age']
map()
Applies a function to each item in an iterable and returns an iterator.
# Double each number in a list
def double(x):
return x * 2
numbers = [1, 2, 3, 4, 5]
doubled = map(double, numbers)
print(list(doubled)) # [2, 4, 6, 8, 10]
# Convert strings to integers
str_nums = ["10", "20", "30", "40"]
int_nums = map(int, str_nums)
print(list(int_nums)) # [10, 20, 30, 40]
# Multiple iterables with a function that takes multiple arguments
def add(x, y):
return x + y
list1 = [1, 2, 3]
list2 = [4, 5, 6]
sums = map(add, list1, list2)
print(list(sums)) # [5, 7, 9]
# Alternative using list comprehension (often preferred)
numbers = [1, 2, 3, 4, 5]
doubled_comp = [x * 2 for x in numbers]
print(doubled_comp) # [2, 4, 6, 8, 10]
int_nums_comp = [int(x) for x in str_nums]
print(int_nums_comp) # [10, 20, 30, 40]
max()
Returns the largest item in an iterable or the largest of multiple arguments.
# Find tallest building height
heights = [381, 828, 508, 632]
print(max(heights)) # 828
# Find room with largest area
rooms = {"living": 24, "bedroom": 15, "kitchen": 16}
largest = max(rooms, key=rooms.get)
print(largest) # "living"
# Find building with maximum height
buildings = [
{"name": "Empire State", "height": 381},
{"name": "Burj Khalifa", "height": 828},
{"name": "Taipei 101", "height": 508}
]
def get_height(building):
return building["height"]
tallest = max(buildings, key=get_height)
print(tallest["name"]) # "Burj Khalifa"
min()
Returns the smallest item in an iterable or the smallest of multiple arguments.
# Find shortest building height
heights = [381, 828, 508, 632]
print(min(heights)) # 381
# Find room with smallest area
rooms = {"living": 24, "bedroom": 15, "kitchen": 16}
smallest = min(rooms, key=rooms.get)
print(smallest) # "bedroom"
# Find building with minimum height
buildings = [
{"name": "Empire State", "height": 381},
{"name": "Burj Khalifa", "height": 828},
{"name": "Taipei 101", "height": 508}
]
def get_height(building):
return building["height"]
shortest = min(buildings, key=get_height)
print(shortest["name"]) # "Empire State"
📦
object()
Creates a simple, base-level Python object with no custom properties or methods. Like a placeholder.
# object() creates a basic object with no attributes
x = object()
y = object()
print(x) # Prints unique object representation
print(type(x)) # Prints <class 'object'>
✨
open()
Creates a file object, allowing you to read from or write to files using different modes ('r' for read, 'w' for write, 'a' for append).
# Recommended way using 'with' context-manager for auto-closing file.
# Read
with open('example.txt', 'r') as file:
content = file.read()
print(content)
# Write
with open('example.txt', 'w') as file:
file.write('Hello, Python!')
# Basic file reading ( NOT RECOMMENDED as file might get corrupted is not closed.)
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
pow()
Raises a number to a specified power, with an optional third argument for modulo calculation.
print(pow(2, 3)) # Output: 8 (2 to the power of 3)
print(pow(2, 3, 5)) # Output: 3 (2^3 modulo 5)
# Alternative
print(2 ** 3) # Output: 8 (same as pow(2, 3))
✨
print()
Outputs text to the console, with options to separate arguments and control line endings.
print("Hello World.")
📦
property()
Decorator that converts method into a property based on its returned value.
class Building:
def __init__(self, name, height_ft):
self.name = name
self.height_ft = height_ft
@property
def height_m(self):
return self.height_ft * 0.3048
skyscraper = Building("EF-Tower", 455)
print(skyscraper.height_m) # Output: 138.684
# 💡 Best for creating properties that require calculation or multiple checks
✨
range()
generates a sequence of numbers with optional start, stop, and step parameters.
# Creating a range of numbers
print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(2, 7))) # Output: [2, 3, 4, 5, 6]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]
# Often used in Loops
for n in range(10):
print(f'Attemprt # {n}')
📦
repr()
Rturns a dev string representation of an object, often used for debugging and development.
class Building:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Building(name='{self.name}')"
def __str__(self):
return f"{self.name} Building"
skyscraper = Building("EF-Tower")
print(repr(skyscraper)) # Output: Building(name='EF-Tower')
print(str(skyscraper)) # Output: EF-Tower Building
print(skyscraper) # Output: EF-Tower Building
reversed()
Reverse the order of items in sequences like lists, tuples and strings .
levels = ["Level 1", "Level 2", "Level 3"]
for level in reversed(levels):
print(level)
# Output:
# Level 3
# Level 2
# Level 1
round()
Return number rounded to X precision after the decimal point. If X is not provided returns the nearest integer to its input.
x = 12.3456776
y = 98.76543
z = 0.1234522222
print(x, y, z)
# Rounded Values
x_ = round(x, 1)
y_ = round(y, 1)
z_ = round(z, 1)
print(x_, y_, z_)
🔹
set()
Convert data into a set. Creates a collection of unique, unordered elements, removing duplicates automatically.
cats = ["Wall", "Door", "Wall", "Floor", "Door"]
unique_cats = set(cats)
print(unique_categories) # Output: {'Wall', 'Door', 'Floor'}
📦
setattr()
Assigns the value to the attribute, provided the object allows it
class Building:
def __init__(self, name):
self.name = name
skyscraper = Building("EF-Tower")
setattr(skyscraper, 'height', 69)
setattr(skyscraper, 'location', 'Tallinn, Estonia')
print(skyscraper.height) # Output: 69
print(skyscraper.location) # Output: Tallinn, Estonia
✨
sorted()
Returns a new sorted list from the given iterable, with optional reverse sorting.
# Sorted - Numeric
numbers = [5, 2, 8, 1, 9]
print(sorted(numbers)) # Output: [1, 2, 5, 8, 9]
print(sorted(numbers, reverse=True)) # Output: [9, 8, 5, 2, 1]
# Sorted - Alphabetic
materials = ['Steel', 'Concrete', 'Wood', 'Brick']
print(sorted(materials)) # Output: ['Brick', 'Concrete', 'Steel', 'Wood']
# Sorting a dictionary by value without lambda or imports
materials = {'Steel': 120,
'Concrete': 75,
'Wood': 40,
'Brick': 95}
# Define a function to return the second element (value)
def get_value(item):
return item[1]
sorted_materials = sorted(materials.items(), key=get_value)
print(sorted_materials) # Output: [('Wood', 40), ('Concrete', 75), ('Brick', 95), ('Steel', 120)]
📦
staticmethod()
Decorator that creates a method that belongs to a class rather than an instance, allowing access without creating an object.
class Converter:
@staticmethod
def fahrenheit_to_celsius(f):
return (f - 32) * 5/9
@staticmethod
def days_to_hours(days):
return days * 24
@staticmethod
def kilometers_to_miles(km):
return km * 0.621371
# Using the static methods
print(Converter.fahrenheit_to_celsius(32)) # Output: 0.0
print(Converter.days_to_hours(2)) # Output: 48
print(Converter.kilometers_to_miles(10)) # Output: 6.21371
🔹
str()
Converts an object to its string representation, using the object's __str__() method if defined.
print(str(123)) # Output: '123'
print(str(3.14)) # Output: '3.14'
print(str([1, 2, 3])) # Output: '[1, 2, 3]'
# OOP __str__ representation of objects
class Building:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Building: {self.name}"
skyscraper = Building("Empire State")
print(str(skyscraper)) # Output: Building: Empire State
sum()
Adds all numbers in an iterable, with an optional start value that defaults to zero.
# Summing numbers in a list
numbers = [1, 2, 3, 4, 5]
print(sum(numbers)) # Output: 15
📦
super()
Function allows calling methods from a parent class, typically used in inheritance to extend or modify inherited behavior.
class Wall:
def __init__(self, height, width, material):
self.height = height
self.width = width
self.material = material
def area(self):
return self.height * self.width
class BrickWall(Wall):
def __init__(self, height, width, brick_type):
super().__init__(height, width, "Brick") # Call __init__ from parent Wall Class
self.brick_type = brick_type
def describe(self):
return f"{self.brick_type} brick wall, {self.height}x{self.width}"
kitchen_wall = BrickWall(3, 4, "Red Clay")
print(kitchen_wall.material) # Output: Brick
print(kitchen_wall.brick_type) # Output: Red Clay
print(kitchen_wall.describe()) # Output: Red Clay brick wall, 3x4
🔹
tuple()
Converts an iterable into a tuple, creating an immutable sequence of elements.
# Creating tuples from different iterables
print(tuple([1, 2, 3])) # Output: (1, 2, 3)
print(tuple('hello')) # Output: ('h', 'e', 'l', 'l', 'o')
# Empty tuple
empty = tuple()
print(empty) # Output: ()
✨
type()
Returns the type of an object, helping identify its data type or class, often use for debugging and understanding variables.
print(type('Hello World')) # <class 'str'>
print(type(69)) # <class 'int'>
print(type([1,2,3])) # <class 'list'>
print(type(None)) # <class 'NoneType'>
📦
vars()
Returns the __dict__ attribute of an object, which contains its instance variables.
class Building:
def __init__(self, name, height):
self.name = name
self.height = height
skyscraper = Building("EF-Tower", 69)
print(vars(skyscraper)) # Output: {'name': '"EF-Tower', 'height': 69}
✨
zip()
Creates an iterator of tuples by combining elements from multiple iterables, useful for pairing related architectural data.
materials = ['Concrete', 'Steel', 'Wood']
strengths = [25, 50, 15]
# Combining materials and their strengths
zip_materials = zip(materials, strengths) #<zip object at 0x7f59a148dcc0>
material_strengths = list(zip_materials)
print(material_strengths) # Output: [('Concrete', 25), ('Steel', 50), ('Wood', 15)]
Homework
Homework
⌨️ Happy Coding!
Questions
Questions
Should I learn all functions?
Should I learn all functions?
When do I need OOP functions?
When do I need OOP functions?
Should I use ChatGPT as beginner?
Should I use ChatGPT as beginner?
Discuss Lesson
P.S. Sometimes this chat might experience connection issues.
Use Discord App for the best experience.
Discuss Lesson
P.S. Sometimes this chat might experience connection issues.
Use Discord App for the best experience.
Discuss Lesson
P.S. Sometimes this chat might experience connection issues.
Use Discord App for the best experience.
Unlock Community
The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.
Use coupon code "upgrade" to get 150EUR Discount as a member.
⌨️ Happy Coding!
Unlock Community
The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.
Use coupon code "upgrade" to get 150EUR Discount as a member.
⌨️ Happy Coding!
Unlock Community
The pyRevit Hackers Community is only available with pyRevit Hackers Bundle.
Upgrade Here to Get Access to the community and all pyRevit Courses.
Use coupon code "upgrade" to get 150EUR Discount as a member.
⌨️ Happy Coding!
© 2023-2025 EF Learn Revit API
© 2023-2025 EF Learn Revit API
© 2023-2025 EF Learn Revit API