Guide to Python's Built-in Functions

Guide to Python's Built-in Functions

Essential Guide to Python's Built-in Functions for Beginners

·

7 min read

Overview

Python offers a set of built-in functions that streamline common programming tasks. This guide categorizes and explains some of these essential functions.

Basic Functions

print(): Prints the specified message to the screen or other standard output device.

print("Hello, World!")  # Output: Hello, World!

input(): Allows the user to take input from the console.

name = input("Enter your name: ")
print(f"Hello, {name}!")

len(): Returns the length (number of items) of an object or iterable.

my_list = [1, 2, 3, 4]
print(len(my_list))  # Output: 4

type(): Returns the type of an object.

print(type(10))      # Output: <class 'int'>
print(type(3.14))    # Output: <class 'float'>
print(type("hello")) # Output: <class 'str'>

id(): Returns a unique id for the specified object.

id(my_list)

repr(): Returns a readable version of an object. ie, returns a printable representation of the object by converting that object to a string

repr(my_list)  # Output: '[1, 2, 3, 4]'

Data Type Conversion

int():Converts a value to an integer.

print(int("123"))  # Output: 123

float()Converts a value to a float.

print(float("123.45"))  # Output: 123.45

str():Converts a value to a string.

print(str(123))  # Output: '123'

bool():Convert any other data type value (string, integer, float, etc) into a boolean data type.

  • False Values: 0, NULL, empty lists, tuples, dictionaries, etc.
  • True Values: All other values will return true.
print(bool(1))  # Output: True

list(): Converts a value to a list.

print(list("hello"))  # Output: ['h', 'e', 'l', 'l', 'o']

tuple(): Converts a value to a tuple.

print(tuple("hello"))  # Output: ('h', 'e', 'l', 'l', 'o')

set(): Converts a value to a list.

print(set("hello"))  # Output: {'e', 'l', 'o', 'h'}

dict(): Used to create a new dictionary or convert other iterable objects into a dictionary.

dict(One = "1", Two = "2")  # Output: {'One': '1', 'Two': '2'}
dict([('a', 1), ('b', 2), ('c', 3)], d=4)  # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Mathematical Functions

abs(): Returns the absolute value of a number.

print(abs(-7))  # Output: 7

round(): Returns the absolute value of a number.

print(round(3.14159, 2))  # Output: 3.14

min(): Returns the smallest item in an iterable or the smallest of two or more arguments.

print(min([1, 2, 3, 4, 5]))  # Output: 1

max(): Returns the largest item in an iterable or the largest of two or more arguments.

print(max([1, 2, 3, 4, 5]))  # Output: 5

sum(): Sums the items of an iterable from left to right and returns the total.

print(sum([1, 2, 3, 4, 5]))  # Output: 15

pow(): Returns the value of a number raised to the power of another number.

print(pow(2, 3))  # Output: 8

Sequence Functions

enumerate(): Adds a counter to an iterable and returns it as an enumerate object.

fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
    print(index, fruit)
# Output:
# 0 apple
# 1 banana
# 2 cherry

zip(): Combines multiple iterables into a single iterator of tuples.

names = ['Alice', 'Bob', 'Charlie']
ages = [24, 50, 18]
for name, age in zip(names, ages):
    print(f"{name} is {age} years old")
# Output:
# Alice is 24 years old
# Bob is 50 years old
# Charlie is 18 years old

sorted(): Returns a sorted list from the elements of any iterable.

print(sorted([5, 2, 9, 1]))  # Output: [1, 2, 5, 9]

reversed(): Returns a reversed iterator.

print(list(reversed([5, 2, 9, 1]))))  
# Output: [1, 9, 2, 5]

range(): Generates a sequence of numbers.

for i in range(5):
    print(i)
# Output: 0, 1, 2, 3, 4

Object and Class Functions

isinstance(): Checks if an object is an instance or subclass of a class or tuple of classes.

class Animal:
    pass

class Dog(Animal):
    pass

dog = Dog()
print(isinstance(dog, Dog))       # True
print(isinstance(dog, Animal))    # True
print(isinstance(dog, str))       # False

issubclass(): Checks if a class is a subclass of another class.

print(issubclass(Dog, Animal))  # True
print(issubclass(Dog, object))  # True
print(issubclass(Animal, Dog))  # False

hasattr(): Checks if an object has a specified attribute.

class Car:
    def __init__(self, model):
        self.model = model

car = Car("Toyota")
print(hasattr(car, "model"))    # True
print(hasattr(car, "color"))    # False

getattr(): Returns the value of a specified attribute of an object.

print(getattr(car, "model"))    # Toyota
print(getattr(car, "color", "Unknown"))  # Unknown (default value)

setattr(): Sets the value of a specified attribute of an object.

setattr(car, "color", "Red")
print(car.color)  # Red

delattr(): Deletes a specified attribute from an object.

delattr(car, "color")
print(hasattr(car, "color"))    # False

Functional Programming

lambda: Used to create small anonymous functions.

add = lambda a, b: a + b
print(add(3, 5))  # 8

map(): Applies a function to all the items in an iterable.

numbers = [1, 2, 3, 4]
squared = map(lambda x: x**2, numbers)
print(list(squared))  # [1, 4, 9, 16]

filter(): Constructs an iterator from elements of an iterable for which a function returns

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers))  # [2, 4, 6]

I/O Operations

open(): Opens a file and returns a corresponding file object. write(): Writes data to a file.

file = open("example.txt", "w")
file.write("Hello, world!")
file.close()

close(): Closes an open file.

file = open("example.txt", "r")
print(file.read())  # Line A\nLine B\nLine C
file.close()
print(file.closed)  # True

read(): Reads data from a file.

file = open("example.txt", "r")
content = file.read()
print(content)  # Hello, world!
file.close()

readline()

file = open("example.txt", "w")
file.write("Line 1\nLine 2\nLine 3")
file.close()

file = open("example.txt", "r")
print(file.readline())  # Line 1
print(file.readline())  # Line 2
file.close()

readlines()

file = open("example.txt", "r")
lines = file.readlines()
print(lines)  # ['Line 1\n', 'Line 2\n', 'Line 3']
file.close()

writelines()

lines = ["Line A\n", "Line B\n", "Line C\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()

file = open("example.txt", "r")
print(file.read())  # Line A\nLine B\nLine C
file.close()

with

with open("example.txt", "w") as file:
    file.write("Hello, world!")
# No need to call file.close(), it's done automatically

Memory Management

del(): Deletes an object.

x = 10
print(x)  # Output: 10
del x
# print(x)  # This will raise a NameError because x is deleted.

globals(): Returns a dictionary representing the current global symbol table.

def example_globals():
    a = 5
    print(globals())
example_globals()
# Output: {'__name__': '__main__', '__doc__': None, ...}

locals(): Updates and returns a dictionary representing the current local symbol table.

def example_locals():
    x = 10
    y = 20
    print(locals())
example_locals()
# Output: {'x': 10, 'y': 20}

vars(): Returns the dict attribute of the given object.

class Example:
    def __init__(self, a, b):
        self.a = a
        self.b = b

e = Example(1, 2)
print(vars(e))  # Output: {'a': 1, 'b': 2}

Miscellaneous

help(): Invokes the built-in help system.

help(len)
# Output: Help on built-in function len in module builtins:
# len(obj, /)
#     Return the number of items in a container.

dir(): Attempts to return a list of valid attributes for an object.

print(dir([]))
# Output: ['__add__', '__class__', '__contains__', ...]

eval(): Parses the expression passed to it and runs Python expression within the program.

x = 1
expression = "x + 1"
result = eval(expression)
print(result)  # Output: 2

exec(): Executes the dynamically created program, which is either a string or a code object.

code = """
for i in range(5):
    print(i)
"""
exec(code)
# Output: 
# 0
# 1
# 2
# 3
# 4

compile(): Compiles source into a code or AST object.

source = "print('Hello, World!')"
code = compile(source, '<string>', 'exec')
exec(code)
# Output: Hello, World!

Conclusion

Python's built-in functions are essential tools that facilitate a wide range of programming tasks. From basic operations to complex functional programming techniques, these functions make Python versatile and powerful. Familiarizing yourself with these functions enhances coding efficiency and effectiveness, enabling you to write cleaner and more maintainable code.

If you have any questions, suggestions, or corrections, please feel free to leave a comment. Your feedback helps me improve and create more accurate content.

Happy coding!!!