Python Built-in Functions

PythonBeginner
Practice Now

Introduction

Welcome to the lab on Python's built-in functions. The Python interpreter provides a rich set of functions and types that are always available, without the need for any imports. These functions are the fundamental building blocks for performing common tasks, from data manipulation to input/output operations.

In this lab, you will get hands-on experience with some of the most essential built-in functions, categorized into logical groups. By the end of this lab, you will be proficient in using these functions to write more efficient and readable Python code.

Data Type Conversion and Inspection

In this step, you will learn to convert between different data types and inspect objects using functions like int(), str(), list(), dict(), type(), and isinstance(). These are fundamental for handling data in Python.

Note: If you are not familiar with using WebIDE (VS Code like), please learn it first at this lab.

First, open the file step1_conversion.py from the file explorer on the left. We will write our code in this file.

Add the following code to step1_conversion.py. This code demonstrates how to convert a string to an integer, a tuple to a list, and a list of pairs to a dictionary. It also shows how to check an object's type.

## step1_conversion.py

## int(): Return an integer object from a number or string.
num_str = "123"
num_int = int(num_str)
print(f"String '{num_str}' as integer: {num_int}")

## str(): Return a string version of an object.
int_val = 456
str_val = str(int_val)
print(f"Integer {int_val} as string: '{str_val}'")

## list(): Create a new list from an iterable.
my_tuple = ('a', 'b', 'c')
my_list = list(my_tuple)
print(f"Tuple {my_tuple} as list: {my_list}")

## dict(): Create a new dictionary.
my_pairs = [('x', 1), ('y', 2)]
my_dict = dict(my_pairs)
print(f"List of pairs {my_pairs} as dict: {my_dict}")

## type(): Return the type of an object.
print(f"Type of num_int: {type(num_int)}")

## isinstance(): Return True if the object is an instance of a class.
is_list = isinstance(my_list, list)
print(f"Is my_list an instance of list? {is_list}")

Now, save the file and run it from the terminal.

python3 step1_conversion.py

You should see the following output, which confirms the data type conversions and inspections were successful.

String '123' as integer: 123
Integer 456 as string: '456'
Tuple ('a', 'b', 'c') as list: ['a', 'b', 'c']
List of pairs [('x', 1), ('y', 2)] as dict: {'x': 1, 'y': 2}
Type of num_int: <class 'int'>
Is my_list an instance of list? True

Mathematical and Numeric Operations

In this step, you will perform common mathematical calculations using built-in functions. We will cover abs(), sum(), min(), max(), round(), and pow().

Open the file step2_math.py from the file explorer.

Add the following code to step2_math.py. This script demonstrates how to apply various mathematical functions to numbers and lists of numbers.

## step2_math.py

numbers = [5, -10, 15, -2, 8]

## abs(): Return the absolute value of a number.
print(f"Absolute value of -10: {abs(-10)}")

## sum(): Sums the items of an iterable.
print(f"Sum of numbers {numbers}: {sum(numbers)}")

## min(): Return the smallest item in an iterable.
print(f"Minimum of numbers: {min(numbers)}")

## max(): Return the largest item in an iterable.
print(f"Maximum of numbers: {max(numbers)}")

## round(): Return number rounded to a given precision.
pi_approx = 3.14159
print(f"Rounding {pi_approx} to 2 decimal places: {round(pi_approx, 2)}")

## pow(): Return base to the power exp.
print(f"2 to the power of 3: {pow(2, 3)}")

Save the file and execute it in the terminal.

python3 step2_math.py

The output should display the results of each mathematical operation.

Absolute value of -10: 10
Sum of numbers [5, -10, 15, -2, 8]: 16
Minimum of numbers: -10
Maximum of numbers: 15
Rounding 3.14159 to 2 decimal places: 3.14
2 to the power of 3: 8

Working with Sequences and Iterables

In this step, you'll learn how to manipulate and process sequences like lists and tuples. We will cover len(), sorted(), reversed(), enumerate(), map(), filter(), and zip(). Many of these functions return iterators, which are efficient, memory-saving objects.

Open the file step3_sequences.py.

Add the following code to step3_sequences.py. This script will demonstrate how to get the length of a list, sort it, reverse it, and perform more complex transformations using map, filter, and zip.

## step3_sequences.py

my_list = [3, 1, 4, 1, 5, 9]
print(f"Original list: {my_list}")

## len(): Return the length (the number of items) of an object.
print(f"Length of the list: {len(my_list)}")

## sorted(): Return a new sorted list from the items in iterable.
print(f"Sorted list: {sorted(my_list)}")

## reversed(): Return a reverse iterator. We convert it to a list to print.
print(f"Reversed list: {list(reversed(my_list))}")

## enumerate(): Return an enumerate object (iterator of index, value pairs).
print(f"Enumerated list: {list(enumerate(my_list))}")

## map(): Return an iterator that applies a function to every item of iterable.
squared_numbers = map(lambda x: x*x, my_list)
print(f"Squared numbers (map): {list(squared_numbers)}")

## filter(): Construct an iterator from elements of iterable for which a function returns true.
even_numbers = filter(lambda x: x % 2 == 0, my_list)
print(f"Even numbers (filter): {list(even_numbers)}")

## zip(): Iterate over several iterables in parallel.
list_a = ['a', 'b', 'c']
list_b = [1, 2, 3]
zipped = zip(list_a, list_b)
print(f"Zipped lists: {list(zipped)}")

Save the file and run it.

python3 step3_sequences.py

You will see the output of various sequence operations. Notice how functions like reversed, map, filter, and zip return iterators, which we convert to lists using list() to display their contents.

Original list: [3, 1, 4, 1, 5, 9]
Length of the list: 6
Sorted list: [1, 1, 3, 4, 5, 9]
Reversed list: [9, 5, 1, 4, 1, 3]
Enumerated list: [(0, 3), (1, 1), (2, 4), (3, 1), (4, 5), (5, 9)]
Squared numbers (map): [9, 1, 16, 1, 25, 81]
Even numbers (filter): [4]
Zipped lists: [('a', 1), ('b', 2), ('c', 3)]

Input Output and Object Representation

In this step, you will handle basic input/output operations and control how objects are represented as strings. We will focus on print(), open(), repr(), and format(). We will also briefly mention input().

Open the file step4_io.py.

The input() function reads a line from the console, converts it to a string, and returns it. For example: name = input("Enter your name: "). We will not use it in our script to avoid pausing execution, but it's a crucial function to know.

Now, add the following code to step4_io.py. This script will write to a file, read from it, and demonstrate different ways to represent and format objects as strings.

## step4_io.py
import datetime

## open(): Open a file and return a corresponding file object.
## We use a 'with' statement to ensure the file is automatically closed.
file_path = "/home/labex/project/my_file.txt"
with open(file_path, "w") as f:
    f.write("Hello, LabEx!\n")
    f.write("This is a test file.")
print(f"Successfully wrote to {file_path}")

## Reading from the file
with open(file_path, "r") as f:
    content = f.read()
    print("--- File Content ---")
    print(content)
    print("--------------------")

## repr(): Return a string containing a printable, unambiguous representation of an object.
now = datetime.datetime(2023, 10, 27, 10, 30, 0)
print(f"str(now): {str(now)}")
print(f"repr(now): {repr(now)}")

## format(): Convert a value to a “formatted” representation.
formatted_string = format(123.4567, ".2f")
print(f"Formatted number (123.4567 to .2f): {formatted_string}")

Save the file and run it from the terminal.

python3 step4_io.py

The script will create and write to my_file.txt, read it back, and print the content. It also shows the difference between str() and repr() for a datetime object and demonstrates number formatting.

Successfully wrote to /home/labex/project/my_file.txt
--- File Content ---
Hello, LabEx!
This is a test file.
--------------------
str(now): 2023-10-27 10:30:00
repr(now): datetime.datetime(2023, 10, 27, 10, 30)
Formatted number (123.4567 to .2f): 123.46

Object Introspection and Metaprogramming

In this final step, you'll explore advanced functions for interacting with object attributes and namespaces. This is often called introspection or reflection. We will use getattr(), hasattr(), setattr(), dir(), globals(), and locals().

Open the file step5_introspection.py.

We will define a simple class and then use introspection functions to dynamically inspect and modify its instances. Add the following code to step5_introspection.py.

## step5_introspection.py

class Person:
    species = "Homo sapiens"
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)

## hasattr(): Return True if the object has the named attribute.
print(f"Does person have 'name' attribute? {hasattr(p, 'name')}")
print(f"Does person have 'height' attribute? {hasattr(p, 'height')}")

## setattr(): This is the counterpart of getattr(). It sets an attribute on an object.
print("Setting attribute 'height' to 175...")
setattr(p, 'height', 175)
print(f"Does person have 'height' attribute now? {hasattr(p, 'height')}")

## getattr(): Return the value of the named attribute of an object.
print(f"Person's name: {getattr(p, 'name')}")
print(f"Person's height: {getattr(p, 'height')}")

## dir(): Return the list of names in the current local scope or an object's attributes.
## We check if 'height' is now in the list of attributes.
print(f"Is 'height' in dir(p)? {'height' in dir(p)}")

## globals(): Return a dictionary of the current global symbol table.
## We'll check if our 'Person' class is in globals.
print(f"Is 'Person' in globals? {'Person' in globals().keys()}")

## locals(): Return a dictionary of the current local symbol table.
def a_func():
    x = 10
    print(f"Is 'x' in locals()? {'x' in locals().keys()}")

a_func()

Save the file and run it.

python3 step5_introspection.py

The output demonstrates how you can dynamically check for, set, and get attributes of an object using their string names. It also shows how to inspect the attributes of an object and the variables available in the global and local scopes.

Does person have 'name' attribute? True
Does person have 'height' attribute? False
Setting attribute 'height' to 175...
Does person have 'height' attribute now? True
Person's name: Alice
Person's height: 175
Is 'height' in dir(p)? True
Is 'Person' in globals? True
Is 'x' in locals()? True

Summary

Congratulations on completing the lab! You have gained practical experience with a wide range of Python's essential built-in functions.

In this lab, you have learned how to:

  • Convert between data types and inspect objects (int, str, type, isinstance).
  • Perform common mathematical operations (abs, sum, min, max, round).
  • Manipulate and process sequences and iterables (len, sorted, map, filter, zip).
  • Handle basic file I/O and object string representation (open, repr, format).
  • Inspect and dynamically modify objects and namespaces (hasattr, getattr, setattr, dir).

These functions are fundamental to everyday Python programming. Mastering them will significantly improve your coding efficiency and readability. Continue to explore other built-in functions and practice using them in your own projects.