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

print(dir(builtins))

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]

reversed(): Returns a list from an iterable in reversed order.

numbers = [3, 1, 4, 1, 5, 9, 2] 
reversed_nums = reversed(numbers) 
print(reversed_nums) 
for i in reversed_nums:
    print(i)

Return a list contain sorted number in descending order.

numbers = [3, 1, 4, 1, 5, 9, 2] 
sorted_nums = sorted(numbers) 
reversed_order = reversed(sorted_nums)
for i in reversed_order:
    print(i)

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.

5. Video Demo for This Article.

You can watch the video of this example article below.

 

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.