Python Built-in Functions

Introduction

Python provides a wide range of built-in functions that can be used directly without needing to import any module. These functions perform various tasks, such as type conversion, mathematical operations, input/output operations, and more. Understanding these built-in functions is crucial for writing efficient and effective Python code.

Commonly Used Built-in Functions

1. Type Conversion Functions

These functions are used to convert data types.

  • int(): Converts a value to an integer.
  • float(): Converts a value to a float.
  • str(): Converts a value to a string.
  • bool(): Converts a value to a boolean.

Examples:

print(int("10"))      # Output: 10
print(float("10.5"))  # Output: 10.5
print(str(100))       # Output: "100"
print(bool(0))        # Output: False

2. Mathematical Functions

These functions perform mathematical operations.

  • abs(): Returns the absolute value of a number.
  • max(): Returns the maximum value in an iterable or among two or more arguments.
  • min(): Returns the minimum value in an iterable or among two or more arguments.
  • sum(): Returns the sum of all items in an iterable.
  • round(): Rounds a number to a specified number of decimal places.

Examples:

print(abs(-7))            # Output: 7
print(max(1, 5, 3, 9, 2)) # Output: 9
print(min(1, 5, 3, 9, 2)) # Output: 1
print(sum([1, 2, 3, 4]))  # Output: 10
print(round(3.14159, 2))  # Output: 3.14

3. Sequence and Collection Functions

These functions operate on sequences and collections like lists, tuples, and sets.

  • len(): Returns the number of items in an object.
  • sorted(): Returns a sorted list of the specified iterable.
  • reversed(): Returns an iterator that accesses the given sequence in the reverse order.
  • enumerate(): Returns an enumerate object containing pairs of index and value.

Examples:

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

for index, value in enumerate(["a", "b", "c"]):
    print(index, value)
# Output:
# 0 a
# 1 b
# 2 c

4. Input/Output Functions

These functions handle input and output operations.

  • print(): Prints to the console.
  • input(): Reads input from the console.

Examples:

print("Hello, World!")       # Output: Hello, World!
name = input("Enter your name: ")
print(f"Hello, {name}!")

5. Object and Type Functions

These functions are used to interact with objects and their types.

  • type(): Returns the type of an object.
  • isinstance(): Checks if an object is an instance of a specified class or type.
  • id(): Returns the unique identifier of an object.

Examples:

print(type(10))               # Output: <class 'int'>
print(isinstance(10, int))    # Output: True
print(id("Hello"))            # Output: (some unique identifier)

6. Miscellaneous Functions

  • dir(): Returns a list of valid attributes of an object.
  • help(): Invokes the built-in help system.
  • hex(): Converts an integer to a hexadecimal string.
  • bin(): Converts an integer to a binary string.

Examples:

print(dir(str))                # Output: (list of string methods)
help(str)                      # Output: (help information for the str class)
print(hex(255))                # Output: '0xff'
print(bin(10))                 # Output: '0b1010'

Practical Examples Using Built-in Functions

Example 1: Calculating the Average of a List

numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print(f"The average is {average}")

Output:

The average is 30.0

Example 2: Converting and Formatting Strings

number = 255
hex_number = hex(number)
print(f"The hexadecimal representation of {number} is {hex_number}")

binary_number = bin(number)
print(f"The binary representation of {number} is {binary_number}")

Output:

The hexadecimal representation of 255 is 0xff
The binary representation of 255 is 0b11111111

Example 3: Sorting and Reversing a List

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print(f"Sorted list: {sorted_numbers}")

reversed_numbers = list(reversed(numbers))
print(f"Reversed list: {reversed_numbers}")

Output:

Sorted list: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
Reversed list: [5, 3, 5, 6, 2, 9, 5, 1, 4, 1, 3]

Example 4: Using enumerate in a for Loop

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

Output:

0: apple
1: banana
2: cherry

Example 5: Using isinstance and type

data = [10, "hello", 3.14, True]
for item in data:
    if isinstance(item, int):
        print(f"{item} is an integer")
    elif isinstance(item, str):
        print(f'"{item}" is a string')
    elif isinstance(item, float):
        print(f"{item} is a float")
    elif isinstance(item, bool):
        print(f"{item} is a boolean")

Output:

10 is an integer
"hello" is a string
3.14 is a float
True is a boolean

Python Built-in Functions Table

Below is a list of some commonly used built-in functions, along with their descriptions and links to detailed guides for each function.

Function Description
abs() Returns the absolute value of a number.
all() Returns True if all elements of an iterable are true.
any() Returns True if any element of an iterable is true.
ascii() Returns a string containing a printable representation of an object.
bin() Converts an integer to a binary string.
bool() Converts a value to a Boolean.
bytearray() Returns a byte array object.
bytes() Returns a bytes object.
callable() Returns True if the object appears callable.
chr() Returns a string representing a character from an integer.
classmethod() Converts a method into a class method.
compile() Compiles source into a code or AST object.
complex() Returns a complex number.
delattr() Deletes an attribute from an object.
dict() Creates a dictionary.
dir() Tries to return a list of valid attributes of an object.
divmod() Returns a tuple containing the quotient and remainder when dividing two numbers.
enumerate() Returns an enumerate object.
eval() Evaluates a given expression.
exec() Executes the given code.
filter() Constructs an iterator from elements of an iterable for which a function returns true.
float() Returns a floating-point number.
format() Formats a specified value.
frozenset() Returns a frozenset object.
getattr() Returns the value of the named attribute of an object.
globals() Returns a dictionary representing the current global symbol table.
hasattr() Returns True if the object has the specified attribute.
hash() Returns the hash value of an object.
help() Invokes the built-in help system.
hex() Converts an integer to a hexadecimal string.
id() Returns the identity of an object.
input() Reads a line from input.
int() Converts a value to an integer.
isinstance() Checks if an object is an instance of a class.
issubclass() Checks if a class is a subclass of another class.
iter() Returns an iterator object.
len() Returns the length of an object.
list() Creates a list.
locals() Updates and returns a dictionary representing the current local symbol table.
map() Applies a function to every item of an iterable.
max() Returns the largest item in an iterable or the largest of two or more arguments.
memoryview() Returns a memory view object.
min() Returns the smallest item in an iterable or the smallest of two or more arguments.
next() Retrieves the next item from an iterator.
object() Returns a new featureless object.
oct() Converts an integer to an octal string.
open() Opens a file and returns a corresponding file object.
ord() Converts a character to its Unicode code.
print() Prints to the standard output device.
property() Returns a property attribute.
range() Returns a sequence of numbers.
reversed() Returns a reversed iterator.
round() Rounds a number to a specified number of digits.
set() Creates a set.
setattr() Sets the value of the specified attribute of an object.
slice() Returns a slice object.
staticmethod() Converts a method into a static method.
str() Returns a string version of an object.
sum() Sums the items of an iterable.
super() Returns a proxy object that delegates method calls to a parent or sibling class.
tuple() Creates a tuple.
type() Returns the type of an object.
vars() Returns the dict attribute of an object.
zip() Returns an iterator of tuples.
import() Invoked by the import statement.

For more detailed information on each function, refer to the official Python documentation.

Conclusion

Python’s built-in functions are powerful tools that can simplify and streamline your coding tasks. By leveraging these functions, you can perform a wide range of operations without needing to import additional modules. Understanding and utilizing built-in functions is essential for efficient and effective Python programming. The provided examples demonstrate practical uses of various built-in functions in different contexts.

Leave a Comment

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

Scroll to Top