Introduction
Python provides a rich set of built-in functions that simplify common programming tasks. These functions are always available, meaning you don't need to import any libraries to use them.
This guide explains the most common built-in functions, grouped by their purpose, and provides practical examples to help you understand how they work.
Input/Output Functions
These functions help you interact with users and display output.
print()
The print()
function outputs data to the console. Use it to display messages or results.
print("Hello, World!")
input()
The input()
function reads user input from the console. It always returns the input as a string.
name = input("Enter your name: ")
print(f"Hello, {name}!")
Type Conversion Functions
These functions convert data from one type to another.
int()
The int()
function converts a value to an integer.
num = int("42")
print(num) # Output: 42
float()
The float()
function converts a value to a floating-point number.
num = float("3.14")
print(num) # Output: 3.14
str()
The str()
function converts a value to a string.
text = str(42)
print(text) # Output: "42"
bool()
The bool()
function converts a value to a boolean.
result = bool(0)
print(result) # Output: False
list()
The list()
function converts an iterable to a list.
my_list = list("hello")
print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']
tuple()
The tuple()
function converts an iterable to a tuple.
my_tuple = tuple([1, 2, 3])
print(my_tuple) # Output: (1, 2, 3)
set()
The set()
function converts an iterable to a set.
my_set = set([1, 2, 2, 3])
print(my_set) # Output: {1, 2, 3}
dict()
The dict()
function creates a dictionary.
my_dict = dict(a=1, b=2)
print(my_dict) # Output: {'a': 1, 'b': 2}
Mathematical Functions
These functions perform mathematical operations.
abs()
The abs()
function returns the absolute value of a number.
print(abs(-10)) # Output: 10
round()
The round()
function rounds a number to the nearest integer or specified decimal places.
print(round(3.14159, 2)) # Output: 3.14
min()
The min()
function returns the smallest item in an iterable.
print(min([3, 1, 4, 1, 5])) # Output: 1
max()
The max()
function returns the largest item in an iterable.
print(max([3, 1, 4, 1, 5])) # Output: 5
sum()
The sum()
function returns the sum of all items in an iterable.
print(sum([1, 2, 3, 4])) # Output: 10
pow()
The pow()
function raises a number to a power.
print(pow(2, 3)) # Output: 8
Iterable and Sequence Functions
These functions work with iterables like lists, tuples, and strings.
len()
The len()
function returns the length of an object.
print(len("hello")) # Output: 5
sorted()
The sorted()
function returns a sorted list from an iterable.
print(sorted([3, 1, 4, 1, 5])) # Output: [1, 1, 3, 4, 5]
reversed()
The reversed()
function returns a reversed iterator.
print(list(reversed([1, 2, 3]))) # Output: [3, 2, 1]
enumerate()
The enumerate()
function adds a counter to an iterable.
for i, value in enumerate(["a", "b", "c"]):
print(i, value)
# Output: 0 a, 1 b, 2 c
zip()
The zip()
function combines multiple iterables into tuples.
print(list(zip([1, 2], ["a", "b"]))) # Output: [(1, 'a'), (2, 'b')]
filter()
The filter()
function filters elements based on a condition.
print(list(filter(lambda x: x > 0, [-1, 0, 1, 2]))) # Output: [1, 2]
map()
The map()
function applies a function to all items in an iterable.
print(list(map(lambda x: x * 2, [1, 2, 3]))) # Output: [2, 4, 6]
Object and Class Functions
These functions work with objects and classes.
type()
The type()
function returns the type of an object.
print(type(42)) # Output: <class 'int'>
isinstance()
The isinstance()
function checks if an object is an instance of a class.
print(isinstance(42, int)) # Output: True
id()
The id()
function returns the memory address of an object.
print(id(42)) # Output: Memory address
hasattr()
The hasattr()
function checks if an object has a specific attribute.
print(hasattr("hello", "upper")) # Output: True
getattr()
The getattr()
function retrieves an attribute from an object.
print(getattr("hello", "upper")()) # Output: "HELLO"
setattr()
The setattr()
function sets an attribute for an object.
class MyClass: pass
obj = MyClass()
setattr(obj, "x", 10)
print(obj.x) # Output: 10
File and I/O Functions
These functions handle file operations.
open()
The open()
function opens a file.
with open("example.txt", "w") as f:
f.write("Hello, World!")
Miscellaneous Functions
These functions don't fit into the above categories.
help()
The help()
function displays documentation for an object.
help(print)
dir()
The dir()
function lists attributes and methods of an object.
print(dir("hello"))
eval()
The eval()
function evaluates a string as Python code.
print(eval("2 + 2")) # Output: 4
exec()
The exec()
function executes a string as Python code.
exec("x = 10")
print(x) # Output: 10
globals()
The globals()
function returns a dictionary of global variables.
print(globals())
locals()
The locals()
function returns a dictionary of local variables.
def my_func():
x = 10
print(locals())
my_func() # Output: {'x': 10}
Conclusion
Python's built-in functions are very powerful because they simplify many common programming tasks. By understanding how to use these functions effectively, you can write cleaner, more efficient code. This guide provides a comprehensive overview of the most commonly used built-in functions, along with practical examples to help you get started.