Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 5 · Python Built-in Functions

Python Built-in Functions

On this pageThe range() FunctionThe sorted() FunctionThe map() FunctionThe filter() FunctionThe random ModuleCombined Random Functions — Random Prize GeneratorSummary

You have already defined functions. Python also provides built-in functions, available without an import, that can help you process values and collections.

They make it easier to perform everyday tasks such as generating sequences, transforming data, or working with collections.

This section focuses on five commonly used built-in functions that appear throughout real-world programs: range(), sorted(), map() and filter(). We then introduce the separate standard-library module random, which must be imported.

The range() Function

The range() function generates a sequence of numbers. It is commonly used in loops or whenever you need to repeat something a specific number of times.

It can be called in three forms:

  • range(stop) → starts at 0, ends before stop
  • range(start, stop) → starts at start, ends before stop
  • range(start, stop, step) → adds a step between numbers

Let’s see it in action:

print(list(range(5)))        # 0 to 4
print(list(range(2, 8)))     # 2 to 7
print(list(range(0, 10, 2))) # even numbers
Listing 219 — The range() Function

Output — one possible run

[0, 1, 2, 3, 4]
[2, 3, 4, 5, 6, 7]
[0, 2, 4, 6, 8]

The first example starts from 0 by default, while the second begins at 2.

The third example introduces a step of 2, producing only even numbers.

The stop value is always excluded, meaning the sequence ends just before it.

The sorted() Function

The sorted() function arranges items in order and returns a new list, leaving the original unchanged. You can also specify whether sorting should be ascending, descending, or follow a custom rule.

numbers = [3, 1, 4, 2]
print(sorted(numbers))               # ascending order
print(sorted(numbers, reverse=True)) # descending order
Listing 220 — The sorted() Function

Output — one possible run

[1, 2, 3, 4]
[4, 3, 2, 1]

Here,sorted() first arranges numbers from smallest to largest, then reverses the order when reverse=True.

You can even sort text by a custom rule using the key parameter.

In this example, words are sorted by length:

words = ["banana", "fig", "apple"]
print(sorted(words, key=len))
Listing 221 — The sorted() Function

Output — one possible run

['fig', 'apple', 'banana']

The map() Function

The map() function applies another function to each element in a sequence.

It takes two arguments: a function and an iterable.

Let’s use it to square all numbers in a list:

def square(x):
    return x ** 2

numbers = [1, 2, 3, 4]
result = map(square, numbers)
print(list(result))
Listing 222 — The map() Function

Output — one possible run

[1, 4, 9, 16]

map() returns an iterator, which supplies results one at a time as requested. list(result) collects those results into a list. This expresses a transformation without an explicit loop.

The filter() Function

The filter() function extracts only the elements that satisfy a condition.

It also takes two arguments: a function that returns True or False, and an iterable.

In the example below, only even numbers are kept.

def is_even(x):
    return x % 2 == 0

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
Listing 223 — The filter() Function

Output — one possible run

[2, 4, 6]

The random Module

The random module lets Python generate pseudorandom numbers and choices, which are essential for games, simulations, and sampling data.

To use it, you must first import it:

import random
Listing 224 — The random Module

Let’s look at the most useful random functions and how their parameters work.

###random.random()

This function returns a floating-point number between 0.0 (inclusive) and 1.0 (exclusive).

It takes no arguments.

print(random.random())
Listing 225 — The random Module

Output — one possible run

0.8533700289991242

Each call generates a new random value, perfect for simulations or percentages.

###random.randint(a, b)

This function returns a random integer between a and b, both included.

It takes two integer arguments:

  • a: the lowest possible value
  • b: the highest possible value
print(random.randint(1, 6))  # simulating a dice roll
Listing 226 — The random Module

Output — one possible run

2

Each time you run it, you’ll get an integer from 1 to 6.

###random.choice(sequence)

This function returns one random element from a given sequence (like a list or tuple).

It takes sequence as argument for the collection to choose from.

fruits = ["apple", "banana", "cherry", "date"]
print(random.choice(fruits))
Listing 227 — The random Module

Output — one possible run

banana

Each time it randomly selects one fruit.

###random.shuffle(list)

This function rearranges the elements of a list in place, meaning it modifies the original list.

It takes a list as its single argument.

cards = ["Ace", "King", "Queen", "Jack"]
random.shuffle(cards)
print(cards)
Listing 228 — The random Module

Output — one possible run

['King', 'Ace', 'Jack', 'Queen']

The order may change; a shuffle can also leave a list in the same order.

Combined Random Functions — Random Prize Generator

Let’s now combine these random functions into a short program that simulates a prize draw at a fair. A few random choices, a number roll, and a lucky probability all come together in one example.

import random

# Step 1: shuffle participant list
participants = ["Anna", "Ben", "Clara", "David", "Ella"]
random.shuffle(participants)
print("Shuffled participants:", participants)

# Step 2: pick a random winner
winner = random.choice(participants)

# Step 3: assign a random prize value between 10 and 100
prize = random.randint(10, 100)

# Step 4: decide if there’s a bonus prize based on probability
bonus_chance = random.random()
if bonus_chance > 0.8:
    print(f"🎉 Congratulations {winner}! You won ${prize} plus a bonus gift!")
else:
    print(f"🎉 Congratulations {winner}! You won ${prize}.")
Listing 229 — Combined Random Functions — Random Prize Generator

Output — one possible run

Shuffled participants: ['Clara', 'Ella', 'David', 'Anna', 'Ben']
🎉 Congratulations Anna! You won $94.

Summary

Built-in functions are the building blocks of many Python programs. They allow you to generate sequences, sort or transform data, while the separate random module supplies pseudorandom values.

You’ll soon combine many of these functions with lambda expressions and user-defined functions to build smart, flexible programs.