DEV Community

Cover image for Python Built-In functions simplified
BrendahKiragu
BrendahKiragu

Posted on

Python Built-In functions simplified

This year, I'm diving into cloud computing. As a starting point, I enrolled in the AWS re/Start Cloud Foundational Course. I'm currently in week 6 of 12 and tackling the Python module. I created this blog as a quick reference for Python built-in functions with examples. Hope it helps someone else.

Table of Contents

1. Type Conversion Functions

These functions convert data from one type to another.

num_str = "100"
num_int = int(num_str)  # Converts string to integer
num_float = float(num_str)  # Converts string to float
bool_val = bool(1)  # Converts integer to boolean (True)
list_val = list("hello")  # Converts string to list of characters
tuple_val = tuple([1, 2, 3])  # Converts list to tuple
set_val = set([1, 2, 2, 3])  # Converts list to set (removes duplicates)
dict_val = dict([(1, 'one'), (2, 'two')])  # Converts list of tuples to dictionary
Enter fullscreen mode Exit fullscreen mode
  • int(x): Converts x to an integer.
  • float(x): Converts x to a floating-point number.
  • str(x): Converts x to a string.
  • bool(x): Converts x to a boolean (True or False).
  • list(iterable): Converts an iterable to a list.
  • tuple(iterable): Converts an iterable to a tuple.
  • set(iterable): Converts an iterable to a set.
  • dict(iterable): Converts an iterable to a dictionary.

2. Mathematical Functions

Python offers built-in math functions to perform calculations.

print(abs(-10))  # Output: 10
print(pow(2, 3))  # Output: 8 (2^3)
print(round(3.14159, 2))  # Output: 3.14
print(max(1, 2, 3))  # Output: 3
print(min(1, 2, 3))  # Output: 1
print(sum([1, 2, 3]))  # Output: 6
print(divmod(10, 3))  # Output: (3, 1) (quotient and remainder)
Enter fullscreen mode Exit fullscreen mode
  • abs(x): Returns the absolute value of x.
  • pow(x, y): Computes x raised to the power y.
  • round(x, n): Rounds x to n decimal places.
  • max(iterable): Returns the largest item in an iterable.
  • min(iterable): Returns the smallest item in an iterable.
  • sum(iterable): Returns the sum of all items in an iterable.
  • divmod(x, y): Returns a tuple of quotient and remainder.

3. Iterables and Sequences

Functions that help manipulate sequences like lists and tuples.

numbers = [1, 2, 3, 4]
print(len(numbers))  # Output: 4
print(sorted(numbers, reverse=True))  # Output: [4, 3, 2, 1]
print(list(reversed(numbers)))  # Output: [4, 3, 2, 1]
print(list(enumerate(numbers)))  # Output: [(0, 1), (1, 2), (2, 3), (3, 4)]
print(list(zip([1, 2], ['a', 'b'])))  # Output: [(1, 'a'), (2, 'b')]
Enter fullscreen mode Exit fullscreen mode
  • len(s): Returns the length of s.
  • sorted(iterable, key=None, reverse=False): Returns a sorted list.
  • reversed(iterable): Returns a reversed iterator.
  • enumerate(iterable, start=0): Returns index-value pairs.
  • zip(*iterables): Combines multiple iterables into tuples.

4. Input and Output

Handling user input and displaying output.

name = input("Enter your name: ")
print(f"Hello, {name}!")
with open("file.txt", "w") as file:
    file.write("Hello, World!")
with open("file.txt", "r") as file:
    print(file.read())  # Output: Hello, World!
Enter fullscreen mode Exit fullscreen mode
  • print(*objects): Prints objects to output.
  • input(prompt): Gets user input as a string.
  • open(file, mode): Opens a file for reading or writing.

5. Object and Type Checking

Verify types and attributes of objects.

print(isinstance(100, int))  # Output: True
print(type("hello"))  # Output: <class 'str'>
print(issubclass(int, object))  # Output: True
print(callable(len))  # Output: True
Enter fullscreen mode Exit fullscreen mode
  • type(object): Returns the type of an object.
  • isinstance(object, classinfo): Checks if an object is an instance of a class.
  • issubclass(class, classinfo): Checks if a class is a subclass of another.
  • callable(object): Checks if an object is callable (e.g., a function).

6. Memory and Object Management

Functions for handling object attributes and memory.

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

car = Car("Toyota")
print(getattr(car, "brand"))  # Output: Toyota
setattr(car, "brand", "Honda")
print(hasattr(car, "brand"))  # Output: True
delattr(car, "brand")
print(hasattr(car, "brand"))  # Output: False
Enter fullscreen mode Exit fullscreen mode
  • getattr(obj, name): Gets an attribute value.
  • setattr(obj, name, value): Sets an attribute.
  • hasattr(obj, name): Checks if an attribute exists.
  • delattr(obj, name): Deletes an attribute.

7. Functional Programming

Useful functions for functional-style programming.

nums = [0, 1, 2, 3]
print(all(nums))  # Output: False
print(any(nums))  # Output: True
print(list(filter(lambda x: x > 1, nums)))  # Output: [2, 3]
print(list(map(lambda x: x * 2, nums)))  # Output: [0, 2, 4, 6]
Enter fullscreen mode Exit fullscreen mode
  • all(iterable): Returns True if all elements are True.
  • any(iterable): Returns True if any element is True.
  • filter(function, iterable): Filters elements based on a function.
  • map(function, iterable): Applies a function to all elements.

8. Other Useful Functions

Miscellaneous functions for various tasks.

print(bin(10))  # Output: '0b101'
print(hex(255))  # Output: '0xff'
print(ord('A'))  # Output: 65
print(chr(65))  # Output: 'A'
Enter fullscreen mode Exit fullscreen mode

Conclusion

Happy coding! 🚀

Top comments (0)