Python
Built-in Functions

Guide to Python Built-in Functions

Python provides a rich set of built-in functions that are readily available for use without the need for any additional imports. These functions are part of the Python language and serve various purposes, making Python a powerful and versatile programming language. In this post, we will explore a wide range of built-in functions, categorized into different groups based on their functionalities. Please note that this is not an exhaustive list of Python built-in functions. Let's dive in!

Mathematical Functions

FunctionDescription
abs()Returns the absolute value of a number.
divmod()Returns the quotient and remainder of the division.
pow()Raises a number to a specified power.
round()Rounds a number to a specified precision.
max()Returns the largest element in a sequence.
min()Returns the smallest element in a sequence.
sum()Returns the sum of elements in a sequence.

Type Conversion Functions

FunctionDescription
int()Converts a number or string to an integer.
float()Converts a number or string to a float.
str()Converts an object to a string.
bool()Converts a value to a Boolean.
list()Converts an iterable to a list.
tuple()Converts an iterable to a tuple.
set()Converts an iterable to a set.
dict()Creates a new dictionary.

Sequence Functions

FunctionDescription
len()Returns the length of a sequence.
sorted()Returns a new sorted list from a sequence.
enumerate()Adds a counter to an iterable and returns an enumerate object.
zip()Combines multiple iterables element-wise.
reversed()Returns a reverse iterator of a sequence.
all()Returns True if all elements are True.
any()Returns True if any element is True.

Input/Output Functions

FunctionDescription
input()Reads a line from input (user).
print()Prints objects to the console.
open()Opens a file and returns a file object.
write()Writes a string to a file.
read()Reads content from a file.
close()Closes a file.
input()Reads a line from input (user).

Object-Oriented Functions

FunctionDescription
isinstance()Checks if an object is an instance of a specified class.
issubclass()Checks if a class is a subclass of a specified class.
getattr()Returns the value of a named attribute of an object.
setattr()Sets the value of a named attribute of an object.
hasattr()Returns True if an object has a given attribute.
id()Returns the identity of an object.

File and Directory Functions

FunctionDescription
open()Opens a file and returns a file object.
read()Reads content from a file.
write()Writes a string to a file.
close()Closes a file.
os.path()Provides functions for working with file paths.
os.listdir()Returns a list of files and directories in a directory.

String Manipulation Functions

FunctionDescription
str()Converts an object to a string.
len()Returns the length of a string.
split()Splits a string into a list of substrings.
join()Joins elements of an iterable into a string.
strip()Removes leading and trailing whitespaces from a string.
find()Searches for a substring in a string and returns its index.
replace()Replaces occurrences of a substring with another substring.

List Manipulation Functions

FunctionDescription
list()Converts an iterable to a list.
len()Returns the number of elements in a list.
append()Adds an element to the end of a list.
extend()Adds elements from an iterable to the end of a list.
insert()Inserts an element at a specified position in a list.
remove()Removes the first occurrence of a value from a list.
pop()Removes and returns an element from a list.
sort()Sorts a list in ascending order.
reverse()Reverses the elements of a list in place.

Tuple Manipulation Functions

FunctionDescription
tuple()Converts an iterable to a tuple.
len()Returns the number of elements in a tuple.
index()Returns the index of the first occurrence of a value in a tuple.
count()Returns the number of occurrences of a value in a tuple.

Dictionary Manipulation Functions

FunctionDescription
dict()Creates a new dictionary.
len()Returns the number of key-value pairs in a dictionary.
keys()Returns a view object of the dictionary's keys.
values()Returns a view object of the dictionary's values.
items()Returns a view object of the dictionary's key-value pairs.
get()Returns the value for a specified key in a dictionary.
update()Updates a dictionary with the key-value pairs from another dictionary.
pop()Removes and returns the value for a specified key in a dictionary.
clear()Removes all key-value pairs from a dictionary.

Set Manipulation Functions

FunctionDescription
set()Converts an iterable to a set.
len()Returns the number of elements in a set.
add()Adds an element to a set.
remove()Removes an element from a set; raises a KeyError if the element is not found.
discard()Removes an element from a set if it exists; does nothing if the element is not found.
pop()Removes and returns an arbitrary element from a set.
union()Returns a new set with elements from both sets.
intersection()Returns a new set with elements common to both sets.
difference()Returns a new set with elements in the set that are not in the other set.

Functional Programming Functions

FunctionDescription
map()Applies a function to all items in an input list and returns an iterator.
filter()Filters elements of an iterable based on a function's condition and returns an iterator.
reduce()Applies a rolling computation to sequential pairs of elements in an iterable.
lambdaCreates an anonymous function (lambda function) for short one-line expressions.

Other Functions

FunctionDescription
type()Returns the type of an object.
id()Returns the identity of an object.
hash()Returns the hash value of an object.
range()Returns a sequence of numbers.
bool()Converts a value to a Boolean.

Please note that this is an exhaustive list of Python built-in functions, covering various categories. Understanding and utilizing these built-in functions will significantly enhance your Python programming capabilities.

Examples of Built-in Functions

Mathematical Functions

1. abs()

The abs() function returns the absolute value of a number.

num = -10
print(abs(num))  # Output: 10
 
num = 5.5
print(abs(num))  # Output: 5.5

2. divmod()

The divmod() function returns the quotient and remainder of the division.

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

3. pow()

The pow() function raises a number to a specified power.

base = 2
exponent = 3
result = pow(base, exponent)
print(result)  # Output: 8
 
# Equivalent to 2^3
result = 2 ** 3
print(result)  # Output: 8

4. round()

The round() function rounds a number to the specified precision (number of decimals).

number = 3.14159
rounded_number = round(number, 2)
print(rounded_number)  # Output: 3.14
 
# If precision is not provided, the number is rounded to the nearest integer.
number = 3.7
rounded_number = round(number)
print(rounded_number)  # Output: 4

5. max()

The max() function returns the largest element in a sequence.

numbers = [10, 5, 8, 3, 12]
largest_number = max(numbers)
print(largest_number)  # Output: 12
 
# The max() function can also accept multiple arguments.
a = 5
b = 10
c = 7
largest_number = max(a, b, c)
print(largest_number)  # Output: 10

6. min()

The min() function returns the smallest element in a sequence.

numbers = [10, 5, 8, 3, 12]
smallest_number = min(numbers)
print(smallest_number)  # Output: 3
 
# The min() function can also accept multiple arguments.
a = 5
b = 10
c = 7
smallest_number = min(a, b, c)
print(smallest_number)  # Output: 5

7. sum()

The sum() function returns the sum of all elements in a sequence.

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

These are examples of how each of the mathematical functions can be used in Python. They provide a useful set of tools for performing mathematical operations efficiently.

Type Conversion Functions

1. int()

The int() function converts a number or a string containing a whole number to an integer.

# Converting a string to an integer
num_str = "42"
integer_num = int(num_str)
print(integer_num)  # Output: 42
 
# Converting a float to an integer
float_num = 3.14
integer_num = int(float_num)
print(integer_num)  # Output: 3
 
# Converting a boolean value to an integer
bool_value = True
integer_num = int(bool_value)
print(integer_num)  # Output: 1

2. float()

The float() function converts a number or a string containing a floating-point number to a float.

# Converting a string to a float
num_str = "3.14"
float_num = float(num_str)
print(float_num)  # Output: 3.14
 
# Converting an integer to a float
integer_num = 42
float_num = float(integer_num)
print(float_num)  # Output: 42.0
 
# Converting a boolean value to a float
bool_value = True
float_num = float(bool_value)
print(float_num)  # Output: 1.0

3. str()

The str() function converts an object to a string.

# Converting an integer to a string
integer_num = 42
str_num = str(integer_num)
print(str_num)  # Output: "42"
 
# Converting a float to a string
float_num = 3.14
str_num = str(float_num)
print(str_num)  # Output: "3.14"
 
# Converting a boolean value to a string
bool_value = True
str_bool = str(bool_value)
print(str_bool)  # Output: "True"

4. bool()

The bool() function converts a value to a Boolean.

# Converting an integer to a boolean
integer_num = 42
bool_value = bool(integer_num)
print(bool_value)  # Output: True
 
# Converting a float to a boolean
float_num = 0.0
bool_value = bool(float_num)
print(bool_value)  # Output: False
 
# Converting an empty string to a boolean
empty_str = ""
bool_value = bool(empty_str)
print(bool_value)  # Output: False

5. list(), tuple(), set()

The list(), tuple(), and set() functions convert an iterable (e.g., list, tuple, string) to a list, tuple, and set, respectively.

# Converting a string to a list of characters
my_string = "hello"
list_chars = list(my_string)
print(list_chars)  # Output: ['h', 'e', 'l', 'l', 'o']
 
# Converting a list to a tuple
my_list = [1, 2, 3, 4]
tuple_numbers = tuple(my_list)
print(tuple_numbers)  # Output: (1, 2, 3, 4)
 
# Converting a tuple to a set
my_tuple = (1, 2, 3, 4)
set_numbers = set(my_tuple)
print(set_numbers)  # Output: {1, 2, 3, 4}

These are examples of how each of the type conversion functions can be used in Python. They are handy tools for converting data between different types, making it easy to work with various data formats in Python.

Sequence Functions

1. len()

The len() function returns the number of elements in a sequence.

my_list = [1, 2, 3, 4, 5]
print(len(my_list))  # Output: 5
 
my_tuple = (10, 20, 30)
print(len(my_tuple))  # Output: 3
 
my_string = "Hello, World!"
print(len(my_string))  # Output: 13

2. sorted()

The sorted() function returns a new sorted list from the elements of any iterable.

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
sorted_list = sorted(my_list)
print(sorted_list)  # Output: [1, 1, 2, 3, 3, 4, 5, 5, 6, 9]
 
my_string = "python"
sorted_string = sorted(my_string)
print(sorted_string)  # Output: ['h', 'n', 'o', 'p', 't', 'y']

3. enumerate()

The enumerate() function adds a counter to an iterable and returns an enumerate object.

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

4. zip()

The zip() function combines multiple iterables element-wise.

names = ['Alice', 'Bob', 'Charlie']
scores = [90, 85, 95]
 
for name, score in zip(names, scores):
    print(name, score)
# Output:
# Alice 90
# Bob 85
# Charlie 95

5. reversed()

The reversed() function returns a reverse iterator of a sequence.

my_list = [1, 2, 3, 4, 5]
reversed_list = reversed(my_list)
print(list(reversed_list))  # Output: [5, 4, 3, 2, 1]
 
my_string = "Hello, World!"
reversed_string = reversed(my_string)
print(''.join(reversed_string))  # Output: "!dlroW ,olleH"

6. all()

The all() function returns True if all elements in the iterable are True.

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

7. any()

The any() function returns True if any element in the iterable is True.

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

These are examples of how each of the sequence functions can be used in Python. They provide powerful tools for working with sequences and iterables efficiently.

Input/Output Functions

1. input()

The input() function reads a line from input (user) and returns it as a string.

name = input("Enter your name: ")
print("Hello, " + name + "!")  # Output: (Depends on user input)

2. print()

The print() function prints objects to the console.

print("Hello, World!")  # Output: Hello, World!
 
age = 25
print("My age is", age)  # Output: My age is 25
 
# Using end parameter to change the line ending (default is '\n')
print("Hello", end=' ')
print("World!")  # Output: Hello World!

3. open(), read(), write(), close()

The file handling functions are used to work with files.

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, File Handling!\n")
 
# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)  # Output: Hello, File Handling!
 
# Appending to a file
with open('example.txt', 'a') as file:
    file.write("Appending new content.\n")
 
# Reading lines from a file
with open('example.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # Output: Hello, File Handling!   (newline)   Appending new content.

File and Directory Functions

os.path()

The os.path() module provides functions for working with file paths.

import os
 
# Get the current working directory
current_dir = os.getcwd()
print(current_dir)  # Output: (Depends on your system)
 
# Joining paths
file_path = os.path.join(current_dir, 'example.txt')
print(file_path)  # Output: (Depends on your system)
 
# Checking if a file exists
file_exists = os.path.exists(file_path)
print(file_exists)  # Output: True (if 'example.txt' exists in the current directory)

User Input and Output functions are essential for making interactive programs and working with files in Python. These functions allow you to get input from users, display information to users, and read and write data from and to files.

Object-Oriented Functions

1. isinstance()

The isinstance() function checks if an object is an instance of a specified class.

class Person:
    pass
 
person = Person()
print(isinstance(person, Person))  # Output: True
 
num = 10
print(isinstance(num, int))  # Output: True
 
name = "John"
print(isinstance(name, str))  # Output: True

2. issubclass()

The issubclass() function checks if a class is a subclass of a specified class.

class Animal:
    pass
 
class Dog(Animal):
    pass
 
print(issubclass(Dog, Animal))  # Output: True
 
print(issubclass(int, object))  # Output: True

3. getattr()

The getattr() function returns the value of a named attribute of an object.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
 
person = Person("Alice", 30)
print(getattr(person, "name"))  # Output: Alice
 
print(getattr(person, "age"))  # Output: 30

4. setattr()

The setattr() function sets the value of a named attribute of an object.

class Person:
    def __init__(self, name):
        self.name = name
 
person = Person("Alice")
 
setattr(person, "name", "Bob")
print(person.name)  # Output: Bob

5. hasattr()

The hasattr() function returns True if an object has a given attribute.

class Person:
    def __init__(self, name):
        self.name = name
 
person = Person("Alice")
 
print(hasattr(person, "name"))  # Output: True
print(hasattr(person, "age"))   # Output: False

6. id()

The id() function returns the identity (unique integer identifier) of an object.

num1 = 10
num2 = num1
 
print(id(num1))  # Output: (Some unique integer value)
print(id(num2))  # Output: (Same unique integer value as num1)

These are examples of how each of the Object-Oriented Functions can be used in Python. They are useful tools for working with objects, classes, and attributes in object-oriented programming.

File and Directory Functions

1. open(), read(), write(), close()

The file handling functions are used to work with files.

# Writing to a file
with open('example.txt', 'w') as file:
    file.write("Hello, File Handling!\n")
 
# Reading from a file
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)  # Output: Hello, File Handling!
 
# Appending to a file
with open('example.txt', 'a') as file:
    file.write("Appending new content.\n")
 
# Reading lines from a file
with open('example.txt', 'r') as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())  # Output: Hello, File Handling!   (newline)   Appending new content.

2. os.path()

The os.path() module provides functions for working with file paths.

import os
 
# Get the current working directory
current_dir = os.getcwd()
print(current_dir)  # Output: (Depends on your system)
 
# Joining paths
file_path = os.path.join(current_dir, 'example.txt')
print(file_path)  # Output: (Depends on your system)
 
# Checking if a file exists
file_exists = os.path.exists(file_path)
print(file_exists)  # Output: True (if 'example.txt' exists in the current directory)

These are examples of how each of the File and Directory Functions can be used in Python. They are valuable tools for reading and writing data to and from files and working with file paths and directories.