Python Built-in Functions With Examples

Built-in functions in Python are functions that are provided as part of the Python language itself, without requiring any external libraries or modules. These functions are available for use without the need for explicit import statements, as they are part of the Python interpreter’s core functionality.

1. What Is Built-in Functions In Python?

Python’s built-in functions cover a wide range of tasks and operations, making common programming tasks more convenient and efficient. These functions can be used to manipulate data, perform calculations, modify strings, manage collections, interact with I/O, and much more. Here are a few examples of categories of built-in functions and what they do.

Basic Operations and Type Conversion:

- `len()`: Returns the length (number of items) of an object.
- `int()`, `float()`, `str()`, etc.: Convert values between different data types.
- `max()` and `min()`: Return the maximum and minimum values in an iterable.

Math and Arithmetic:

- `abs()`: Returns the absolute value of a number.
- `round()`: Rounds a number to a specified number of decimal places.
- `sum()`: Returns the sum of all items in an iterable.

String Manipulation:

- `len()`: Returns the length (number of characters) of a string.
- `str()`: Converts objects to string representation.
- `join()`: Joins a sequence of strings with a specified delimiter.

Collection Operations:

- `list()`, `tuple()`, `set()`, `dict()`: Create new data structures.
- `sorted()`: Returns a sorted version of a sequence.
- `zip()`: Combines multiple iterables into tuples of corresponding elements.

Input and Output:

- `print()`: Outputs text to the console.
- `input()`: Reads user input from the console.

Type Checking and Conversion:

- `type()`: Returns the type of an object.
- `isinstance()`: Checks if an object is an instance of a specified class.

Iteration and Iterables:

- `range()`: Generates a sequence of numbers.
- `enumerate()`: Provides an index along with the value from an iterable.

These are just a few examples of the many built-in functions that Python provides. They serve as the foundation for writing efficient and concise Python code, allowing programmers to perform a wide variety of tasks without having to reinvent the wheel for common operations.

2. How To Get The List Of Python Built-in Functions Using Python Source Code.

You can use the `dir()` function to get a list of all attributes of a module, including the built-in functions. Here’s how you can use it to get a list of all the built-in functions in Python:

import builtins

builtin_functions = [func for func in dir(builtins) if callable(getattr(builtins, func))]

print(builtin_functions)

When you run this code, it will print a list of all the built-in functions available in Python’s `builtins` module.

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'NotADirectoryError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__import__', '__loader__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

Please note that this list includes not only functions specific to lists but all built-in functions available in Python.

3. Python Built-in Functions Examples.

Here’s a list of some commonly used built-in functions for Python along with examples.

print(): Used to display output to the console.

print("Hello, world!")

len(): Returns the number of items in a container (string, list, tuple, etc.).

text = "Python"
length = len(text)
print(length) # Output: 6

input(): Reads user input from the console.

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

str(): Converts objects into a string representation.

number = 42
text = str(number)
print(text) # Output: "42"

int(): Converts a string or a number to an integer.

text = "123"
number = int(text)
print(number + 10) # Output: 133

float(): Converts a string or a number to a floating-point number.

text = "3.14"
pi = float(text)
print(pi + 0.1) # Output: 3.24

list(): Creates a list from an iterable.

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

tuple(): Creates a tuple from an iterable.

coordinates = tuple((3, 7))
print(coordinates) # Output: (3, 7)

dict(): Creates a dictionary.

person = dict(name="Alice", age=30)
print(person) # Output: {'name': 'Alice', 'age': 30}

max() and min(): Returns the maximum or minimum value from an iterable.

numbers = [5, 2, 8, 1]
max_num = max(numbers)
min_num = min(numbers)
print(max_num, min_num) # Output: 8 1

sum(): Returns the sum of all elements in an iterable.

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

sorted(): Returns a sorted list from an iterable.

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

len(): Returns the number of items in a list.

my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print(length) # Output: 5

append(): Adds an item to the end of the list.

my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]

extend(): Appends the elements of another iterable to the list.

my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list) # Output: [1, 2, 3, 4, 5, 6]

insert(): Inserts an element at a specified position.

my_list = [1, 2, 3]
my_list.insert(1, 5)
print(my_list) # Output: [1, 5, 2, 3]

remove(): Removes the first occurrence of a value from the list.

my_list = [1, 2, 3, 2, 4]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2, 4]

pop(): Removes and returns the element at a specified index.

my_list = [1, 2, 3, 4]
removed_item = my_list.pop(2)
print(my_list) # Output: [1, 2, 4]
print(removed_item) # Output: 3

index(): Returns the index of the first occurrence of a value.

my_list = [10, 20, 30, 20, 40]
index = my_list.index(20)
print(index) # Output: 1

count(): Returns the number of occurrences of a value in the list.

my_list = [1, 2, 2, 3, 2, 4]
count = my_list.count(2)
print(count) # Output: 3

sort(): Sorts the list in place.

my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 2, 3, 4, 5, 5, 6, 9]

reverse(): Reverses the elements of the list in place.

my_list = [1, 2, 3, 4, 5]
my_list.reverse()
print(my_list) # Output: [5, 4, 3, 2, 1]

copy(): Creates a shallow copy of the list.

my_list = [1, 2, 3]
new_list = my_list.copy()
print(new_list) # Output: [1, 2, 3]

Remember that these are just a few examples, and Python provides many more built-in functions for various tasks.

4. How To Get Python Builtin Function Help Document?

To get the help document of a Python built-in function, you can use the help() function. Here’s an example:

>>> help(str.upper)

Help on method_descriptor:

upper(self, /)
    Return a copy of the string converted to uppercase.

This will provide you with information about the upper method of the str class, including its parameters, return value, and a brief description.

You can also get the help document of a specific built-in function by using its name as the argument of help(). For example:

>>> help(len)

Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

This will provide you with information about the len function, including its parameters, return value, and a brief description.

The help document typically includes the following information:

The name of the function or method.
A brief description of its purpose and behavior.
The parameters the function takes, along with their default values (if any).
The return value of the function.
Any exceptions the function may raise.
Any related notes or examples (if available).

You can find more detailed information about Python built-in functions and classes in the official Python documentation, which can be accessed online.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.