October 13, 2024

Python Built-in Functions

Python provides a rich set of built-in functions that are always available for use. These functions perform a wide variety of tasks, from basic input/output operations to more complex tasks like mathematical calculations, data type conversions, and working with sequences. Below is a categorized overview of some of the most commonly used built-in functions in Python:

1. Input/Output Functions

  • print(): Outputs data to the console.

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

  • input(): Reads input from the user as a string.

name = input("Enter your name: ")
print("Hello, " + name)

2. Type Conversion Functions

  • int(): Converts a value to an integer.

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

  • float(): Converts a value to a floating-point number.

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

  • str(): Converts a value to a string.

num = 123
num_str = str(num)
print(num_str) # Output: '123'

  • bool(): Converts a value to a Boolean (True or False).

print(bool(0)) # Output: False
print(bool(1)) # Output: True
print(bool("")) # Output: False

  • list(): Converts an iterable to a list.

num_list = list(range(5))
print(num_list) # Output: [0, 1, 2, 3, 4]

  • tuple(): Converts an iterable to a tuple.

num_tuple = tuple([1, 2, 3])
print(num_tuple) # Output: (1, 2, 3)

  • set(): Converts an iterable to a set (removes duplicates).

num_set = set([1, 2, 2, 3, 4, 4])
print(num_set) # Output: {1, 2, 3, 4}

  • dict(): Converts a sequence of key-value pairs to a dictionary.

num_dict = dict([('a', 1), ('b', 2)])
print(num_dict) # Output: {'a': 1, 'b': 2}

3. Mathematical Functions

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

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

  • round(): Rounds a number to a given precision.

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

    • pow(): Returns the value of x raised to the power of y.

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

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

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

 

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

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

  • sum(): Sums the items of an iterable.

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

  • divmod(): Returns a tuple containing the quotient and remainder when dividing two numbers.

quotient, remainder = divmod(10, 3)
print(quotient, remainder) # Output: 3 1

4. Sequence Functions

  • len(): Returns the number of items in an object.

print(len("Hello")) # Output: 5
print(len([1, 2, 3])) # Output: 3

  • range(): Generates a sequence of numbers.

print(list(range(5))) # Output: [0, 1, 2, 3, 4]
print(list(range(1, 10, 2))) # Output: [1, 3, 5, 7, 9]

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

items = ["apple", "banana", "cherry"]
for index, value in enumerate(items):
print(index, value)
# Output:
# 0 apple
# 1 banana
# 2 cherry

  • sorted(): Returns a sorted list from the items in an iterable.

numbers = [4, 2, 5, 1, 3]
print(sorted(numbers)) # Output: [1, 2, 3, 4, 5]

  • reversed(): Returns a reversed iterator of a sequence.

print(list(reversed([1, 2, 3, 4]))) # Output: [4, 3, 2, 1]

  • zip(): Aggregates elements from two or more iterables (like lists or tuples) and returns an iterator of tuples.

names = ["Alice", "Bob", "Charlie"]
scores = [85, 90, 75]
combined = list(zip(names, scores))
print(combined) # Output: [('Alice', 85), ('Bob', 90), ('Charlie', 75)]

5. Logic and Control Flow Functions

  • all(): Returns True if all elements in an iterable are true (or if the iterable is empty).

print(all([True, True, True])) # Output: True
print(all([True, False, True])) # Output: False

  • any(): Returns True if any element in an iterable is true. If the iterable is empty, returns False.

print(any([False, False, True])) # Output: True
print(any([False, False, False])) # Output: False

  • bool(): Converts a value to a Boolean (True or False).

print(bool(1)) # Output: True
print(bool(0)) # Output: False

6. Object and Variable Functions

  • type(): Returns the type of an object.

print(type(5)) # Output: <class 'int'>
print(type("Hello")) # Output: <class 'str'>

  • id(): Returns the unique identifier of an object.

a = 10
print(id(a)) # Output: Unique memory address of the object

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

print(isinstance(5, int)) # Output: True
print(isinstance("Hello", str)) # Output: True

  • callable(): Returns True if the object appears callable (like a function), otherwise returns False.
def my_function():
    pass

print(callable(my_function))  # Output: True
print(callable(5))  # Output: False

7. File Handling Functions

  • open(): Opens a file and returns a file object.

file = open("example.txt", "r")
content = file.read()
file.close()
print(content)

8. Advanced and Miscellaneous Functions

  • eval(): Evaluates a string expression and returns the result.

x = 5
print(eval("x + 2")) # Output: 7

  • exec(): Executes the dynamically created Python code, which can be a string or object code.

code = """

  • a = 5 b = 10 print(a + b) “”” exec(code) # Output: 15

- **`help()`**: Invokes the built-in help system and provides information on the specified object or module.

```python
help(print)  # Displays information about the print function
  • dir(): Returns a list of valid attributes for an object.

print(dir(list)) # Output: List of methods and attributes of the list class

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

print(globals()) # Output: Dictionary of global variables and functions

  • locals(): Returns a dictionary representing the current local symbol table.
def my_function():
    a = 5
    print(locals())

my_function()  # Output: Dictionary of local variables in the function

9. Memory-Related Functions

  • memoryview(): Returns a memory view object from a given object (allows you to access the internal data of an object that supports the buffer protocol).

byte_data = b'hello'
mem_view = memoryview(byte_data)
print(mem_view[0]) # Output: 104 (ASCII value of 'h')

  • bytearray(): Returns a bytearray object, which is a mutable sequence of bytes.

ba = bytearray([1, 2, 3, 4])
print(ba) # Output: bytearray(b'\x01\x02\x03\x04')

  • bytes(): Returns an immutable bytes object.

b = bytes([1, 2, 3, 4])
print(b) # Output: b'\x01\x02\x03\x04'

10. Functional Programming Tools

  • map(): Applies a function to all the items in an input list.
def square(x):
    return x ** 2

result = map(square, [1, 2, 3, 4])
print(list(result))  # Output: [1, 4, 9, 16]
  • filter(): Filters the elements of an iterable based on a function.
def is_even(x):
    return x % 2 == 0

result = filter(is_even, [1, 2, 3, 4])
print(list(result))  # Output: [2, 4]
  • reduce(): Applies a rolling computation to sequential pairs of values in an iterable.
from functools import reduce

def add(x, y):
    return x + y

result = reduce(add, [1, 2, 3, 4])
print(result)  # Output: 10
  • zip(): Aggregates elements from two or more iterables and returns an iterator of tuples.

a = [1, 2, 3]
b = [4, 5, 6]
zipped = zip(a, b)
print(list(zipped)) # Output: [(1, 4), (2, 5), (3, 6)]

11. Decorators

  • @property: Used to define a method in a class that can be accessed like an attribute.
class MyClass:
    def __init__(self, value):
        self._value = value

    @property
    def value(self):
        return self._value

obj = MyClass(10)
print(obj.value)  # Output: 10
  • @staticmethod: Used to define a static method in a class (a method that does not operate on instances).
class MyClass:
@staticmethod
def greet():
return "Hello!"

print(MyClass.greet()) # Output: Hello!

Python’s built-in functions provide powerful tools that can greatly simplify coding tasks and improve productivity. Understanding and utilizing these functions effectively can enhance your programming efficiency, allowing you to write more concise and readable code. These built-in functions cover a wide range of tasks, from basic input/output and type conversions to more advanced tasks like functional programming and memory management.