Python Built-in Functions: Examples & Explanations

Python Built-in Functions: Examples & Explanations

CodeProgrammer

Python Built-in Function: abs()
Explanation: Returns the absolute value of a number. For complex numbers, it returns the magnitude.
Example:

x = -7
y = 3.14
z = -5 + 12j
print(f"Absolute value of {x}: {abs(x)}")
print(f"Absolute value of {y}: {abs(y)}")
print(f"Magnitude of {z}: {abs(z)}")

Output:
Absolute value of -7: 7
Absolute value of 3.14: 3.14
Magnitude of (-5+12j): 13.0

Python Built-in Function: all()
Explanation: Returns True if all elements of an iterable are true (or if the iterable is empty).
Example:

list1 = [True, True, True]
list2 = [True, False, True]
list3 = []
print(f"Are all elements in {list1} true? {all(list1)}")
print(f"Are all elements in {list2} true? {all(list2)}")
print(f"Are all elements in {list3} true? {all(list3)}")

Output:
Are all elements in [True, True, True] true? True
Are all elements in [True, False, True] true? False
Are all elements in [] true? True

Python Built-in Function: any()
Explanation: Returns True if any element of an iterable is true. If the iterable is empty, returns False.
Example:

list1 = [True, False, False]
list2 = [False, False, False]
list3 = []
print(f"Is any element in {list1} true? {any(list1)}")
print(f"Is any element in {list2} true? {any(list2)}")
print(f"Is any element in {list3} true? {any(list3)}")

Output:
Is any element in [True, False, False] true? True
Is any element in [False, False, False] true? False
Is any element in [] true? False

Python Built-in Function: bin()
Explanation: Converts an integer to a binary string prefixed with "0b".
Example:

num1 = 10
num2 = -5
print(f"Binary of {num1}: {bin(num1)}")
print(f"Binary of {num2}: {bin(num2)}")

Output:
Binary of 10: 0b1010
Binary of -5: -0b101

Python Built-in Function: bool()
Explanation: Converts a value to a boolean, using standard truthiness rules. Empty sequences, None, 0, and False are False; everything else is True.
Example:

print(f"bool(0): {bool(0)}")
print(f"bool(1): {bool(1)}")
print(f"bool(''): {bool('')}")
print(f"bool('hello'): {bool('hello')}")
print(f"bool([]): {bool([])}")
print(f"bool([1]): {bool([1])}")
print(f"bool(None): {bool(None)}")

Output:
bool(0): False
bool(1): True
bool(''): False
bool('hello'): True
bool([]): False
bool([1]): True
bool(None): False

Python Built-in Function: breakpoint()
Explanation: Activates the debugger at the call site.
Example:

def my_function(a, b):
result = a + b
# breakpoint() # Uncomment to activate debugger here
return result * 2
# my_function(5, 3)
print("Breakpoint example commented out. If uncommented, it launches a debugger.")

Output:
Breakpoint example commented out. If uncommented, it launches a debugger.

Python Built-in Function: chr()
Explanation: Returns the string representation of a character whose Unicode code point is the integer i.
Example:

print(f"Character for code point 65: {chr(65)}")
print(f"Character for code point 97: {chr(97)}")
print(f"Character for code point 8364: {chr(8364)}") # Euro sign

Output:
Character for code point 65: A
Character for code point 97: a
Character for code point 8364: €

Python Built-in Function: complex()
Explanation: Returns a complex number with the value real + imag*1j. If the first argument is a string, it will be interpreted as a complex number.
Example:

c1 = complex(2, 3)
c2 = complex('1+2j')
c3 = complex(5) # real part only
print(f"Complex number (2,3): {c1}")
print(f"Complex number from string '1+2j': {c2}")
print(f"Complex number from 5: {c3}")

Output:
Complex number (2,3): (2+3j)
Complex number from string '1+2j': (1+2j)
Complex number from 5: (5+0j)

Python Built-in Function: dict()
Explanation: Creates a new dictionary. It can be initialized from keyword arguments, a mapping, or an iterable of key-value pairs.
Example:

d1 = dict()
d2 = dict(a=1, b=2)
d3 = dict([('c', 3), ('d', 4)])
print(f"Empty dict: {d1}")
print(f"Dict from keyword args: {d2}")
print(f"Dict from iterable of pairs: {d3}")

Output:
Empty dict: {}
Dict from keyword args: {'a': 1, 'b': 2}
Dict from iterable of pairs: {'c': 3, 'd': 4}

Python Built-in Function: dir()
Explanation: Without arguments, returns the list of names in the current local scope. With an argument, returns a list of valid attributes for that object.
Example:

my_list = [1, 2]
print(f"Attributes of my_list: {dir(my_list)[:5]}...") # Show first 5 attributes

Output:
Attributes of my_list: ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__']...

Python Built-in Function: divmod()
Explanation: Takes two numbers and returns their quotient and remainder as a tuple.
Example:

quotient, remainder = divmod(10, 3)
print(f"10 divided by 3: Quotient={quotient}, Remainder={remainder}")

Output:
10 divided by 3: Quotient=3, Remainder=1

Python Built-in Function: enumerate()
Explanation: Adds a counter to an iterable and returns it as an enumerate object, yielding (index, item) pairs.
Example:

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")

Output:
Index 0: apple
Index 1: banana
Index 2: cherry

Python Built-in Function: eval()
Explanation: Evaluates a Python expression or statement represented as a string.
Example:

expression = "10 + 5 * 2"
result = eval(expression)
print(f"Result of '{expression}': {result}")

Output:
Result of '10 + 5 * 2': 20

Python Built-in Function: exec()
Explanation: Executes Python code dynamically from a string or code object. Unlike eval(), exec() can execute statements.
Example:

code_to_execute = "a = 7; b = 3; print(a * b)"
exec(code_to_execute)

Output:
21

Python Built-in Function: filter()
Explanation: Constructs an iterator from elements of an iterable for which a function returns true.
Example:

def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(is_even, numbers))
print(f"Even numbers from {numbers}: {even_numbers}")

Output:
Even numbers from [1, 2, 3, 4, 5, 6]: [2, 4, 6]

Python Built-in Function: float()
Explanation: Returns a floating point number constructed from a number or string.
Example:

f1 = float(10)
f2 = float("3.14")
f3 = float("-2.5e-1")
print(f"Float from int 10: {f1}")
print(f"Float from string '3.14': {f2}")
print(f"Float from string '-2.5e-1': {f3}")

Output:
Float from int 10: 10.0
Float from string '3.14': 3.14
Float from string '-2.5e-1': -0.25

Python Built-in Function: format()
Explanation: Converts a value to a "formatted" representation as controlled by format_spec.
Example:

num = 123.45678
formatted_str = format(num, '.2f') # Two decimal places
print(f"Formatted number: {formatted_str}")

Output:
Formatted number: 123.46

Python Built-in Function: getattr()
Explanation: Returns the value of the named attribute of an object. An optional default value can be provided.
Example:

class MyObject:
def __init__(self):
self.value = 10
obj = MyObject()
v1 = getattr(obj, 'value')
v2 = getattr(obj, 'non_existent', 'default')
print(f"Value of 'value' attribute: {v1}")
print(f"Value of 'non_existent' attribute (with default): {v2}")

Output:
Value of 'value' attribute: 10
Value of 'non_existent' attribute (with default): default

Python Built-in Function: hasattr()
Explanation: Returns True if the object has the named attribute, False otherwise.
Example:

class MyObject:
def __init__(self):
self.data = 10
obj = MyObject()
print(f"Does obj have 'data' attribute? {hasattr(obj, 'data')}")
print(f"Does obj have 'method' attribute? {hasattr(obj, 'method')}")

Output:
Does obj have 'data' attribute? True
Does obj have 'method' attribute? False

Python Built-in Function: help()
Explanation: Invokes the built-in help system. Prints documentation for an object if an argument is given.
Example:

# help(len) # Uncomment to see help for len function
print("Used help(len) (commented out for conciseness)")

Output:
Used help(len) (commented out for conciseness)

Python Built-in Function: input()
Explanation: Reads a line from sys.stdin. Takes an optional string as a prompt.
Example:

# name = input("Enter your name: ")
# print(f"Hello, {name}!")
print("Input example commented out. If run, would prompt for name.")

Output:
Input example commented out. If run, would prompt for name.

Python Built-in Function: int()
Explanation: Returns an integer object. Converts a number or string to an integer, with an optional base for strings.
Example:

i1 = int(3.14)
i2 = int("100")
i3 = int("101", 2) # Binary to int
print(f"Int from float 3.14: {i1}")
print(f"Int from string '100': {i2}")
print(f"Int from binary string '101': {i3}")

Output:
Int from float 3.14: 3
Int from string '100': 100
Int from binary string '101': 5

Python Built-in Function: isinstance()
Explanation: Returns True if the object argument is an instance of the classinfo argument, or of a subclass thereof.
Example:

num = 10
text = "hello"
print(f"Is {num} an int? {isinstance(num, int)}")
print(f"Is {text} a list? {isinstance(text, list)}")

Output:
Is 10 an int? True
Is hello a list? False

Python Built-in Function: issubclass()
Explanation: Returns True if class_x is a subclass (direct or indirect) of class_y.
Example:

class Parent: pass
class Child(Parent): pass
print(f"Is Child a subclass of Parent? {issubclass(Child, Parent)}")
print(f"Is Parent a subclass of Child? {issubclass(Parent, Child)}")

Output:
Is Child a subclass of Parent? True
Is Parent a subclass of Child? False

Python Built-in Function: iter()
Explanation: Returns an iterator object for an iterable.
Example:

my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(f"First element: {next(my_iterator)}")
print(f"Second element: {next(my_iterator)}")

Output:
First element: 1
Second element: 2

Python Built-in Function: len()
Explanation: Returns the length (the number of items) of an object.
Example:

my_list = [1, 2, 3, 4]
my_string = "Python"
my_dict = {'a': 1, 'b': 2}
print(f"Length of {my_list}: {len(my_list)}")
print(f"Length of '{my_string}': {len(my_string)}")
print(f"Length of {my_dict}: {len(my_dict)}")

Output:
Length of [1, 2, 3, 4]: 4
Length of 'Python': 6
Length of {'a': 1, 'b': 2}: 2

Python Built-in Function: list()
Explanation: Creates a new list. It can be initialized from an iterable or as an empty list.
Example:

l1 = list()
l2 = list("hello")
l3 = list(range(3))
print(f"Empty list: {l1}")
print(f"List from string 'hello': {l2}")
print(f"List from range(3): {l3}")

Output:
Empty list: []
List from string 'hello': ['h', 'e', 'l', 'l', 'o']
List from range(3): [0, 1, 2]

Python Built-in Function: map()
Explanation: Applies a given function to all items in an iterable and returns a map object (an iterator).
Example:

def square(num):
return num * num
numbers = [1, 2, 3, 4]
squared_numbers = list(map(square, numbers))
print(f"Squared numbers from {numbers}: {squared_numbers}")

Output:
Squared numbers from [1, 2, 3, 4]: [1, 4, 9, 16]

Python Built-in Function: max()
Explanation: Returns the largest item in an iterable or the largest of two or more arguments.
Example:

numbers = [10, 5, 20, 15]
print(f"Max in {numbers}: {max(numbers)}")
print(f"Max of 5, 12, 3: {max(5, 12, 3)}")

Output:
Max in [10, 5, 20, 15]: 20
Max of 5, 12, 3: 12

Python Built-in Function: min()
Explanation: Returns the smallest item in an iterable or the smallest of two or more arguments.
Example:

numbers = [10, 5, 20, 15]
print(f"Min in {numbers}: {min(numbers)}")
print(f"Min of 5, 12, 3: {min(5, 12, 3)}")

Output:
Min in [10, 5, 20, 15]: 5
Min of 5, 12, 3: 3

Python Built-in Function: next()
Explanation: Retrieves the next item from an iterator. Raises StopIteration if exhausted, unless a default is provided.
Example:

my_iterator = iter([10, 20])
print(f"Next item: {next(my_iterator)}")
print(f"Next item: {next(my_iterator)}")
print(f"Next item (with default): {next(my_iterator, 'End')}")

Output:
Next item: 10
Next item: 20
Next item (with default): End

Python Built-in Function: open()
Explanation: Opens a file and returns a file object.
Example:

# import os
# with open('test_file.txt', 'w') as f:
# f.write("Hello from open()!")
# with open('test_file.txt', 'r') as f:
# content = f.read()
# print(f"File content: {content}")
# if os.path.exists('test_file.txt'):
# os.remove('test_file.txt')
print("Open file example commented out for execution safety.")

Output:
Open file example commented out for execution safety.

Python Built-in Function: ord()
Explanation: Returns an integer representing the Unicode code point of the character.
Example:

print(f"Unicode code point of 'A': {ord('A')}")
print(f"Unicode code point of '€': {ord('€')}")

Output:
Unicode code point of 'A': 65
Unicode code point of '€': 8364

Python Built-in Function: pow()
Explanation: Returns x to the power y. With three arguments, returns (x**y) % z.
Example:

print(f"2 to the power 3: {pow(2, 3)}")
print(f"2 to the power 3 modulo 3: {pow(2, 3, 3)}") # (2**3) % 3 = 8 % 3 = 2

Output:
2 to the power 3: 8
2 to the power 3 modulo 3: 2

Python Built-in Function: print()
Explanation: Prints objects to the text stream sys.stdout.
Example:

print("Hello", "World", sep='-')
print("Python is fun", end='!')
print(" Really.")

Output:
Hello-World
Python is fun! Really.

Python Built-in Function: range()
Explanation: Returns an immutable sequence object producing numbers from start (inclusive) to stop (exclusive) with a given step.
Example:

r = range(5) # 0, 1, 2, 3, 4
print(f"List from range(5): {list(r)}")
r2 = range(1, 10, 2) # 1, 3, 5, 7, 9
print(f"List from range(1, 10, 2): {list(r2)}")

Output:
List from range(5): [0, 1, 2, 3, 4]
List from range(1, 10, 2): [1, 3, 5, 7, 9]

Python Built-in Function: repr()
Explanation: Returns a string containing a printable representation of an object, often allowing eval() to reconstruct it.
Example:

my_list = [1, 2, 'hello']
print(f"repr of {my_list}: {repr(my_list)}")

Output:
repr of [1, 2, 'hello']: "[1, 2, 'hello']"

Python Built-in Function: round()
Explanation: Rounds a number to a specified number of decimal places.
Example:

print(f"Round 3.14159 to 2 decimal places: {round(3.14159, 2)}")
print(f"Round 2.5: {round(2.5)}") # Rounds to nearest even integer (2)
print(f"Round 3.5: {round(3.5)}") # Rounds to nearest even integer (4)

Output:
Round 3.14159 to 2 decimal places: 3.14
Round 2.5: 2
Round 3.5: 4

Python Built-in Function: set()
Explanation: Returns a new set object, containing unique elements from an iterable.
Example:

my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(f"Set from {my_list}: {my_set}")

Output:
Set from [1, 2, 2, 3, 4, 4, 5]: {1, 2, 3, 4, 5}

Python Built-in Function: setattr()
Explanation: Sets the value of the named attribute of an object.
Example:

class MyObject: pass
obj = MyObject()
setattr(obj, 'new_attribute', 'hello')
print(f"Value of new_attribute: {obj.new_attribute}")

Output:
Value of new_attribute: hello

Python Built-in Function: sorted()
Explanation: Returns a new sorted list from the items in an iterable.
Example:

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(f"Original list: {numbers}")
print(f"Sorted list: {sorted_numbers}")

Output:
Original list: [3, 1, 4, 1, 5, 9, 2]
Sorted list: [1, 1, 2, 3, 4, 5, 9]

Python Built-in Function: str()
Explanation: Returns a string version of an object.
Example:

s1 = str(123)
s2 = str([1, 2, 3])
print(f"String from int 123: {s1}")
print(f"String from list [1, 2, 3]: {s2}")

Output:
String from int 123: 123
String from list [1, 2, 3]: [1, 2, 3]

Python Built-in Function: sum()
Explanation: Sums start and the items of an iterable from left to right and returns the total.
Example:

numbers = [1, 2, 3, 4, 5]
total_sum = sum(numbers)
total_with_start = sum(numbers, 10) # Start sum from 10
print(f"Sum of {numbers}: {total_sum}")
print(f"Sum of {numbers} starting from 10: {total_with_start}")

Output:
Sum of [1, 2, 3, 4, 5]: 15
Sum of [1, 2, 3, 4, 5] starting from 10: 25

Python Built-in Function: super()
Explanation: Returns a proxy object that delegates method calls to a parent or sibling class.
Example:

class Parent:
def greet(self):
return "Hello from Parent"
class Child(Parent):
def greet(self):
parent_greeting = super().greet()
return f"{parent_greeting} and from Child!"
child_obj = Child()
print(child_obj.greet())

Output:
Hello from Parent and from Child!

Python Built-in Function: tuple()
Explanation: Creates a new tuple. It can be initialized from an iterable or as an empty tuple.
Example:

t1 = tuple()
t2 = tuple([1, 2, 3])
t3 = tuple("abc")
print(f"Empty tuple: {t1}")
print(f"Tuple from list [1, 2, 3]: {t2}")
print(f"Tuple from string 'abc': {t3}")

Output:
Empty tuple: ()
Tuple from list [1, 2, 3]: (1, 2, 3)
Tuple from string 'abc': ('a', 'b', 'c')

Python Built-in Function: type()
Explanation: With one argument, returns the type of an object.
Example:

num = 10
my_list = [1, 2]
print(f"Type of {num}: {type(num)}")
print(f"Type of {my_list}: {type(my_list)}")

Output:
Type of 10: <class 'int'>
Type of [1, 2]: <class 'list'>

Python Built-in Function: zip()
Explanation: Creates an iterator that aggregates elements from multiple iterables into tuples.
Example:

names = ['Alice', 'Bob']
ages = [25, 30]
zipped_data = list(zip(names, ages))
print(f"Zipped data from names and ages: {zipped_data}")

Output:
Zipped data from names and ages: [('Alice', 25), ('Bob', 30)]

Python Built-in Function: ValueError()
Explanation: Raised when an operation or function receives an argument that has the right type but an inappropriate value.
Example:

try:
int("abc")
except ValueError as e:
print(f"Caught value error: {e}")

Output:
Caught value error: invalid literal for int() with base 10: 'abc'

Python Built-in Function: TypeError()
Explanation: Raised when an operation or function is applied to an object of an inappropriate type.
Example:

try:
"hello" + 5
except TypeError as e:
print(f"Caught type error: {e}")

Output:
Caught type error: can only concatenate str (not "int") to str

Python Built-in Function: KeyError()
Explanation: Raised when a mapping (dictionary) key is not found.
Example:

my_dict = {'a': 1, 'b': 2}
try:
print(my_dict['c'])
except KeyError as e:
print(f"Caught key error: {e}")

Output:
Caught key error: 'c'

Python Built-in Function: IndexError()
Explanation: Raised when a sequence subscript is out of range.
Example:

my_list = [1, 2, 3]
try:
print(my_list[5])
except IndexError as e:
print(f"Caught index error: {e}")

Output:
Caught index error: list index out of range

Python Built-in Function: MemoryError()
Explanation: Raised when an operation runs out of memory.
Example:

# try:
# a = [0] * (10**10) # Attempt to allocate huge list
# except MemoryError as e:
# print(f"Caught memory error: {e}")
print("MemoryError example commented out (might crash system if run).")

Output:
MemoryError example commented out (might crash system if run).

Python Built-in Function: FileNotFoundError()
Explanation: Raised when a file or directory is requested but doesn't exist.
Example:

try:
with open('non_existent_file.txt', 'r') as f:
f.read()
except FileNotFoundError as e:
print(f"Caught file not found error: {e}")

Output:
Caught file not found error: [Errno 2] No such file or directory: 'non_existent_file.txt'

(Output message may vary based on OS)

Python Built-in Function: ZeroDivisionError()
Explanation: Raised when the second argument of a division or modulo operation is zero.
Example:

try:
10 / 0
except ZeroDivisionError as e:
print(f"Caught zero division error: {e}")

Output:
Caught zero division error: division by zero

Python Built-in Function: NameError()
Explanation: Raised when a local or global name is not found.
Example:

try:
print(undefined_variable)
except NameError as e:
print(f"Caught name error: {e}")

Output:
Caught name error: name 'undefined_variable' is not defined

Python Built-in Function: OSError()
Explanation: Base class for I/O related errors.
Example:

try:
raise OSError("A generic OS error occurred.")
except OSError as e:
print(f"Caught OS error: {e}")

Output:
Caught OS error: A generic OS error occurred.

Python Built-in Function: RecursionError()
Explanation: Raised when the interpreter detects that the recursion depth is exceeded.
Example:

def infinite_recursion():
infinite_recursion()
try:
infinite_recursion()
except RecursionError as e:
print(f"Caught recursion error: {e}")

Output:
Caught recursion error: maximum recursion depth exceeded

Python Built-in Function: StopIteration()
Explanation: Must be raised by the __next__() method of an iterator to signal no further items.
Example:

my_iterator = iter([1, 2])
try:
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator)) # This will raise StopIteration
except StopIteration as e:
print(f"Caught stop iteration: {e}")

Output:
1
2
Caught stop iteration:

#Python #BuiltinFunctions #PythonTips #Programming #Coding #PythonBasics #Reference #BeginnerFriendly #InterviewPrep #PythonEssentials

Report Page