DEV Community

Cover image for Essential Guide to Python's Built-in Functions for Beginners
Varsha VM
Varsha VM

Posted on

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

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!
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

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'>
Enter fullscreen mode Exit fullscreen mode

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

id(my_list)
Enter fullscreen mode Exit fullscreen mode

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]'
Enter fullscreen mode Exit fullscreen mode

Data Type Conversion

int():Converts a value to an integer.

print(int("123"))  # Output: 123
Enter fullscreen mode Exit fullscreen mode

float()Converts a value to a float.

print(float("123.45"))  # Output: 123.45
Enter fullscreen mode Exit fullscreen mode

str():Converts a value to a string.

print(str(123))  # Output: '123'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

list(): Converts a value to a list.

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

tuple(): Converts a value to a tuple.

print(tuple("hello"))  # Output: ('h', 'e', 'l', 'l', 'o')
Enter fullscreen mode Exit fullscreen mode

set(): Converts a value to a list.

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

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}
Enter fullscreen mode Exit fullscreen mode

Mathematical Functions

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

print(abs(-7))  # Output: 7
Enter fullscreen mode Exit fullscreen mode

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

print(round(3.14159, 2))  # Output: 3.14
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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

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

print(pow(2, 3))  # Output: 8
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

print(sorted([5, 2, 9, 1]))  # Output: [1, 2, 5, 9]
Enter fullscreen mode Exit fullscreen mode

reversed(): Returns a reversed iterator.

print(list(reversed([5, 2, 9, 1]))))  
# Output: [1, 9, 2, 5]
Enter fullscreen mode Exit fullscreen mode

range(): Generates a sequence of numbers.

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

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

print(getattr(car, "model"))    # Toyota
print(getattr(car, "color", "Unknown"))  # Unknown (default value)
Enter fullscreen mode Exit fullscreen mode

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

setattr(car, "color", "Red")
print(car.color)  # Red
Enter fullscreen mode Exit fullscreen mode

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

delattr(car, "color")
print(hasattr(car, "color"))    # False
Enter fullscreen mode Exit fullscreen mode

Functional Programming

lambda: Used to create small anonymous functions.

add = lambda a, b: a + b
print(add(3, 5))  # 8
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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()
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

read(): Reads data from a file.

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

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()
Enter fullscreen mode Exit fullscreen mode

readlines()

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

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()
Enter fullscreen mode Exit fullscreen mode

with

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

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.
Enter fullscreen mode Exit fullscreen mode

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

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

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}
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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

print(dir([]))
# Output: ['__add__', '__class__', '__contains__', ...]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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

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!!!

Top comments (1)

Collapse
 
sreno77 profile image
Scott Reno

Awesome post! I would warn the reader to be very careful when using eval and exec because they can be dangerous if you don't know where the data comes from.