Overview of Python Built-in Modules
Overview of Python Built-in Modules
Built-in modules
The Python Standard Library is a collection of built-in functions and modules that support common
programming tasks. Ex: The math module provides functions like sqrt() and constants like pi. Python's
official documentation includes a library reference ([Link] and a module index
([Link] for becoming familiar with the standard library.
Module Description
CONCEPTS IN PRACTICE
Built-in modules
Use the library reference, module index, and documentation links above to answer the questions.
Third-party modules
The Python Package Index (PyPI), available at [Link] ([Link] is the official third-
party software library for Python. The abbreviation "PyPI" is pronounced like pie pea eye (in contrast to PyPy
([Link] a different project).
PyPI allows anyone to develop and share modules with the Python community. Module authors include
individuals, large companies, and non-profit organizations. PyPI helps programmers install modules and
receive updates.
Most software available on PyPI is free and open source. PyPI is supported by the Python Software Foundation
([Link] and is maintained by an independent group of developers.
Module Description
Module Description
CONCEPTS IN PRACTICE
Third-party modules
Use [Link] and the links in the table above to answer the questions.
6. Search for the webcolors module on PyPI. What function provided by webcolors looks up the color
name for a hex code?
a. hex_to_name
b. name_to_hex
c. normalize_hex
EXPLORING FURTHER
Programming blogs often highlight PyPI modules to demonstrate the usefulness of Python. The following
examples provide more background information about the modules listed above.
TRY IT
Happy birthday
Module documentation pages often include examples to help programmers become familiar with the
module. For this exercise, refer to the following examples from the datetime module documentation:
Write a program that creates a date object representing your birthday. Then get a date object
representing today's date (the date the program is run). Calculate the difference between the two dates,
and output the results in the following format:
TRY IT
Notice how leap years are included in the calculation. February 29th occurs four times between birth and
today. Therefore, the user is not only 15 years old, but 15 years and 4 days old.
Many commonly used modules from PyPI, including arrow, are installed in the Python shell at [Link]/
shell ([Link] Open the Python shell and type the following lines:
import arrow
birth = [Link](2005, 3, 14)
[Link]()
As time permits, experiment with other functions provided by the arrow module.
• Programs can be organized into multiple .py files (modules). The import keyword allows a program to use
functions defined in another .py file.
• The from keyword can be used to import specific functions from a module. However, programs should
avoid importing (or defining) multiple functions with the same name.
• Modules often include the line if __name__ == "__main__" to prevent code from running as a side
effect when the module is imported by other programs.
• When working in a shell, the help() function can be used to look up the documentation for a module.
The documentation is generated from the docstrings.
• Python comes with over 200 built-in modules and hundreds of thousands of third-party modules.
Programmers can search for modules on [Link] ([Link] and
[Link] ([Link]
Statement Description
if __name__ == A line of code found at the end of many modules. This statement indicates what
"__main__": code to run if the module is executed as a program (in other words, what code
not to run if this module is imported by another program).
Statement Description
Shows the documentation for the given module. The documentation includes
help(module_name) the module's docstring, followed by a list of functions defined in the module,
followed by a list of global variables assigned in the module, followed by the
module's file name.
Figure 8.1 credit: modification of work "Project 366 #65: 050316 A Night On The Tiles", by Pete/Flickr, CC BY 2.0
Chapter Outline
8.1 String operations
8.2 String slicing
8.3 Searching/testing strings
8.4 String formatting
8.5 Splitting/joining strings
8.6 Chapter summary
Introduction
A string is a sequence of characters. Python provides useful methods for processing string values. In this
chapter, string methods will be demonstrated including comparing string values, string slicing, searching,
testing, formatting, and modifying.
String comparison
String values can be compared using logical operators (<, <=, >, >=, ==, !=) and membership operators (in and
not in). When comparing two string values, the matching characters in two string values are compared
sequentially until a decision is reached. For comparing two characters, ASCII values are used to apply logical
operators.
198 8 • Strings
Checks whether the Since string "bc" does not contain string
second operand "a" in
in False "a", the output of "a" in "bc" evaluates
contains the first "bc"
to False.
operand.
Checks whether the Since string "bc" does not contain string
second operand does "a" not
not in True "a", the output of "a" not in "bc"
not contain the first in "bc"
evaluates to True.
operand.
CONCEPTS IN PRACTICE
EXAMPLE 8.1
x = "Apples"
apples
APPLES
CONCEPTS IN PRACTICE
b. ABBA
c. ABbA
d. aBBA
TRY IT
TRY IT
What is my character?
Given the string, s_input, which is a one-character string object, if the character is between "a" and "t"
or "A" and "T", print True. Otherwise, print False.
Hint: You can convert s_input to lowercase and check if s_input is between "a" and "t".
String indexing
A string is a type of sequence. A string is made up of a sequence of characters indexed from left to right,
starting at 0. For a string variable s, the left-most character is indexed 0 and the right-most character is
indexed len(s) - 1. Ex: The length of the string "Cloud" is 5, so the last index is 4.
Negative indexing can also be used to refer to characters from right to left starting at -1. For a string variable
s, the left-most character is indexed -len(s) and the right-most character is indexed -1. Ex: The length of the
string "flower" is 6, so the index of the first character with negative indexing is -6.
CHECKPOINT
String indexing
Access multimedia content ([Link]
8-2-string-slicing)
CONCEPTS IN PRACTICE
word = "chance"
print(word[-1] == word[5])
a. True
b. False
String slicing
String slicing is used when a programmer must get access to a sequence of characters. Here, a string slicing
operator can be used. When [a:b] is used with the name of a string variable, a sequence of characters
starting from index a (inclusive) up to index b (exclusive) is returned. Both a and b are optional. If a or b are not
provided, the default values are 0 and len(string), respectively.
EXAMPLE 8.2
time_string = "13:46"
minutes = time_string[3:5]
print(minutes)
202 8 • Strings
46
EXAMPLE 8.3
time_string = "14:50"
hour = time_string[:2]
print(hour)
14
CONCEPTS IN PRACTICE
a. "el"
b. "ll"
c. "llo"
location = "classroom"
print(location[-3:-1])
a. "ro"
b. "oo"
c. "oom"
a. " Leila"
b. "Leila"
c. "ila"
String immutability
String objects are immutable meaning that string objects cannot be modified or changed once created. Once
a string object is created, the string's contents cannot be altered by directly modifying individual characters or
elements within the string. Instead, to make changes to a string, a new string object with the desired changes
is created, leaving the original string unchanged.
CHECKPOINT
CONCEPTS IN PRACTICE
string_variable = "example"
string_variable[-1] = ""
a. TypeError
b. IndexError
c. NameError
str = "morning"
str = str[1]
print(str)
204 8 • Strings
a. TypeError
b. m
c. o
TRY IT
TRY IT
Input:
string_variable = "great"
indices = [0, 1]
prints eat
in operator
The in Boolean operator can be used to check if a string contains another string. in returns True if the first
string exists in the second string, False otherwise.
CHECKPOINT
CONCEPTS IN PRACTICE
CHECKPOINT
CONCEPTS IN PRACTICE
for c in "string":
print(c, end = "")
a. string
b. s
t
r
i
n
g
c. s t r i n g
count = 0
for c in "abca":
if c == "a":
count += 1
print(count)
a. 0
b. 1
c. 2
word = "cab"
for i in word:
if i == "a":
print("A", end = "")
if i == "b":
print("B", end = "")
if i == "c":
print("C", end = "")
a. cab
b. abc
c. CAB
d. ABC
count()
The count() method counts the number of occurrences of a substring in a given string. If the given substring
does not exist in the given string, the value 0 is returned.
CHECKPOINT
CONCEPTS IN PRACTICE
find()
The find() method returns the index of the first occurrence of a substring in a given string. If the substring
does not exist in the given string, the value of -1 is returned.
CHECKPOINT
CONCEPTS IN PRACTICE
a. 0
b. -1
c. ValueError
index()
The index() method performs similarly to the find() method in which the method returns the index of the
first occurrence of a substring in a given string. The index() method assumes that the substring exists in the
given string; otherwise, throws a ValueError.
EXAMPLE 8.4
50
CONCEPTS IN PRACTICE
c. ValueError
a. "This"
b. "This "
c. "sentence"
TRY IT
prints:
2
Thisisgreat
format. The example below shows two string values that use the same template for making requests to
different individuals for taking different courses.
EXAMPLE 8.5
Dear John, I'd like to take a programming course with Prof. Potter.
Dear Kishwar, I'd like to take a math course with Prof. Robinson.
In the example above, replacement fields are 1) the name of the individual the request is being made to, 2)
title of the course, and 3) the name of the instructor. To create a template, replacement fields can be added
with {} to show a placeholder for user input. The format() method is used to pass inputs for replacement
fields in a string template.
EXAMPLE 8.6
print(s)
print([Link]("John", "programming", "Potter"))
print([Link]("Kishwar", "math", "Robinson"))
CONCEPTS IN PRACTICE
b. Hello Ana
c. Hello Ana!
EXAMPLE 8.7
print(s)
print([Link](season = "summer", temperature = "hot"))
print([Link](season = "winter", temperature = "cold"))
Since named replacement fields are referred to using a name key, a named replacement field can appear
and be used more than once in the template. Also, positional ordering is not necessary when named
replacement fields are used.
212 8 • Strings
print(s)
print([Link](season = "summer", temperature = "hot"))
print([Link](temperature = "cold", season = "winter"))
CONCEPTS IN PRACTICE
greeting = "Hi"
name = "Jess"
print("{greeting} {name}".format(greeting = greeting, name = name))
a. greeting name
b. Hi Jess
c. Jess Hi
Home".
Numbered replacement fields can use argument's values for multiple replacement fields by using the same
argument index. The example below illustrates how an argument is used for more than one numbered
replacement field.
EXAMPLE 8.8
print([Link]("very", "cold"))
print([Link]("very", "hot"))
EXAMPLE 8.9
In the example above, the table is formatted into three columns. The first column takes up 15 characters and is
left-aligned. The second column uses 25 characters and is center-aligned, and the last column uses two
characters and is right aligned. Alignment and length format specifications controls are used to create the
214 8 • Strings
formatted table.
The field width in string format specification is used to specify the minimum length of the given string. If the
string is shorter than the given minimum length, the string will be padded by space characters. A field width
is included in the format specification field using an integer after a colon. Ex: {name:15} specifies that the
minimum length of the string values that are passed to the name field is 15.
Since the field width can be used to specify the minimum length of a string, the string can be padded with
space characters from right, left, or both to be left-aligned, right-aligned, and centered, respectively. The
string alignment type is specified using <, >, or ^characters after the colon when field length is specified. Ex:
{name:^20} specifies a named replacement field with the minimum length of 20 characters that is center-
aligned.
Alignment
Symbol Example Output
Type
template = "{hex:<7}{name:<10}"
Left- print([Link](hex = "#FF0000", #FF0000Red
<
aligned name = "Red")) print([Link](hex #00FF00green
= "#00FF00", name = "green"))
template = "{hex:>7}{name:>10}"
Right- print([Link](hex = "#FF0000", #FF0000 Red
>
aligned name = "Red")) print([Link](hex #00FF00 green
= "#00FF00", name = "green"))
template = "{hex:^7}{name:^10}"
print([Link](hex = "#FF0000", #FF0000 Red
Centered ^ name = "Red")) print([Link](hex #00FF00 green
= "#00FF00", name = "green"))
CONCEPTS IN PRACTICE
template = "{name:12}"
formatted_name = [Link](name = "Alice")
print(len(formatted_name))
a. 5
b. 12
c. "Alice"
template = "{greeting:>6}"
formatted_greeting = [Link](greeting = "Hello")
print(formatted_greeting[0])
a. H
b. " Hello"
c. Space character
template = "{:5}"
print([Link]("123456789"))
a. 56789
b. 123456
c. 123456789
Formatting numbers
The format() method can be used to format numerical values. Numerical values can be padded to have a
given minimum length, precision, and sign character. The syntax for modifying numeric values follows the
{[index]:[width][.precision][type]} structure. In the given syntax,
The table below summarizes formatting options for modifying numeric values.
CONCEPTS IN PRACTICE
TRY IT
Input: [12.5, 2]
Prints: 012.50
002:00
split()
A string in Python can be broken into substrings given a delimiter. A delimiter is also referred to as a
separator. The split() method, when applied to a string, splits the string into substrings by using the given
argument as a delimiter. Ex: "1-2".split('-') returns a list of substrings ["1", "2"]. When no arguments
are given to the split() method, blank space characters are used as delimiters. Ex: "1\t2\n3 4".split()
returns ["1", "2", "3", "4"].
CHECKPOINT
CONCEPTS IN PRACTICE
s = """This is a test"""
out = [Link]()
print(out)
a. Error
b. ['This', 'is', 'a', 'test']
c. >['This', 'is a', 'test']
join()
The join() method is the inverse of the split() method: a list of string values are concatenated together to
form one output string. When joining string elements in the list, the delimiter is added in-between elements.
Ex: ','.join(["this", "is", "great"]) returns "this,is,great".
CHECKPOINT
CONCEPTS IN PRACTICE
print(",".join(elements))
b. 5
c. 8
s = ["1", "2"]
out = "".join(s)
a. 12
b. "12"
c. "1 2"
TRY IT
happy
smiling
face
TRY IT
Lunch order
Use the join() method to repeat back a user's order at a restaurant, separated by commas. The user will
input each food item on a separate line. When finished ordering, the user will enter a blank line. The output
depends on how many items the user orders:
In the general case with three or more items, each item should be separated by a comma and a space. The
word "and" should be added before the last item.
8-5-splittingjoining-strings)
At this point, you should be able to write programs dealing with string values.
Method Description
find() Returns the index of the first occurrence of a given substring in a string. If the substring
does not exist in the string, -1 is returned.
Returns the index of the first occurrence of a given substring in a string. If the substring
index()
does not exist in the string, a ValueError is returned.
join() Takes a list of string values and combines string values into one string by placing a given
separator between values.
split() Separates a string into tokens based on a given separator string. If no separator string is
provided, blank space characters are used as separators.
Operator Description
Method Description
Figure 9.1 credit: modification of work "Budget and Bills" by Alabama Extension/Flickr, Public Domain
Chapter Outline
9.1 Modifying and iterating lists
9.2 Sorting and reversing lists
9.3 Common list operations
9.4 Nested lists
9.5 List comprehensions
9.6 Chapter summary
Introduction
Programmers often work on collections of data. Lists are a useful way of collecting data elements. Python lists
are extremely flexible, and, unlike strings, a list's contents can be changed.
The Objects chapter introduced lists. This chapter explores operations that can be performed on lists.
EXAMPLE 9.1
Line 8 shows the append() operation, line 12 shows the remove() operation, and line 17 shows the pop()
operation. Since the pop() operation removes the last element, no parameter is needed.
CONCEPTS IN PRACTICE
Modifying lists
1. Which operation can be used to add an element to the end of a list?
a. add()
b. append()
c. pop()
2. What is the correct syntax to remove the element 23 from a list called number_list?
a. remove()
b. number_list.remove()
c. number_list.remove(23)
3. Which operation can be used to remove an element from the end of a list?
a. only pop()
b. only remove()
c. either pop() or remove()
Iterating lists
An iterative for loop can be used to iterate through a list. Alternatively, lists can be iterated using list indexes
with a counting for loop. The animation below shows both ways of iterating a list.
CHECKPOINT
CONCEPTS IN PRACTICE
Iterating lists
For the following questions, consider the list:
my_list = [2, 3, 5, 7, 9]
5. What is the final value of i for the following counting for loop?
for i in range(0, len(my_list)):
a. 9
b. 4
c. 5
a. 2 5 9
b. 2 3 5 7 9
226 9 • Lists
c. 2
5
9
TRY IT
Sports list
Create a list of sports played on a college campus. The sports to be included are baseball, football, tennis,
and table tennis.
Next, remove "football" from the list and add "soccer" to the list.
TRY IT
Simple Searching
Write a program that prints "found!" if "soccer" is found in the given list.
Sorting
Ordering elements in a sequence is often useful. Sorting is the task of arranging elements in a sequence in
ascending or descending order.
Sorting can work on numerical or non-numerical data. When ordering text, dictionary order is used. Ex: "bat"
comes before "cat" because "b" comes before "c".
CHECKPOINT
Sorting
Access multimedia content ([Link]
9-2-sorting-and-reversing-lists)
CONCEPTS IN PRACTICE
Sorting
1. What would be the last element of the following list if it is sorted in descending order?
[12, 3, 19, 25, 16, -3, 5]
a. 25
b. -3
c. 5
• The sort() method arranges the elements of a list in ascending order. For strings, ASCII values are used
and uppercase characters come before lowercase characters, leading to unexpected results. Ex: "A" is
ordered before "a" in ascending order but so is "G"; thus, "Gail" comes before "apple".
• The reverse() method reverses the elements in a list.
EXAMPLE 9.2
CONCEPTS IN PRACTICE
4. What is the correct way to sort the list board_games in ascending order?
a. sort(board_games)
b. board_games.sort()
c. board_games.sort('ascending')
6. What would be the last element of board_games after the reverse() method has been applied?
a. 'go'
b. 'checkers'
c. 'scrabble'
TRY IT
The sum() function called on a list of numbers returns the sum of all elements in the list.
EXAMPLE 9.3
print(min(city_list))
999
Sacramento
-5
Austin
1135
CONCEPTS IN PRACTICE
List operations
1. What is the correct way to get the minimum of a list named nums_list?
a. min(nums_list)
b. nums_list.min()
c. minimum(nums_list)
Copying a list
The copy() method is used to create a copy of a list.
CHECKPOINT
Copying a list
Access multimedia content ([Link]
9-3-common-list-operations)
CONCEPTS IN PRACTICE
Copying a list
4. What is the output of the following code?
my_list = [1, 2, 3]
list2 = my_list
list2[0] = 13
print(sum(my_list))
a. 6
b. 13
c. 18
my_list = [1, 2, 3]
list2 = my_list.copy()
list2[0] = 13
print(max(my_list))
a. 3
b. 13
c. 18
a. CatDogPigeon
b. Error
TRY IT
Copy
Make a copy of word_list called wisdom. Sort the list called wisdom. Create a sentence using the words in
each list and print those sentences (no need to add periods at the end of the sentences).
List-of-lists
Lists can be made of any type of element. A list element can also be a list. Ex: [2, [3, 5], 17] is a valid list
with the list [3, 5] being the element at index 1.
When a list is an element inside a larger list, it is called a nested list. Nested lists are useful for expressing
multidimensional data. When each of the elements of a larger list is a smaller list, the larger list is called a list-
of-lists.
Ex: A table can be stored as a two-dimensional list-of-lists, where each row of data is a list in the list-of-lists.
CHECKPOINT
List-of-lists
Access multimedia content ([Link]
9-4-nested-lists)
CONCEPTS IN PRACTICE
Lists
For each of the questions below, consider the following matrix:
2. What would be the correct index for the number 6 in the above list?
a. [5]
b. [2][1]
c. [1][2]
print(matA[0])
a. Error
b. 7
c. [7, 4, 5]
EXAMPLE 9.4
Iterating a list-of-lists
The code below demonstrates how to iterate a list-of-lists.
The outer loop on line 9 goes element by element for the larger list. Each element in the larger list is a list.
The inner loop on line 10 iterates through each element in each nested list.
1 """Iterating a list-of-lists."""
2
3 # Create a list of numbers
4 list1 = [[1, 2, 3],
5 [1, 4, 9],
6 [1, 8, 27]]
7
8 # Iterating the list-of-lists
9 for row in list1:
10 for num in row:
11 print(num, end=" ")
12 print()
1 2 3
1 4 9
1 8 27
CONCEPTS IN PRACTICE
Iterating a list-of-lists
For each question below, consider the following list:
4. Which code prints each number in my_list starting from 7, then 4, and so on ending with -5?
a. for row in my_list:
for elem in row:
print(elem)
b. for elem in my_list:
print(elem)
5. The range() function can also be used to iterate a list-of-lists. Which code prints each number in
my_list starting from 7, then 4, and so on, ending with -5, using counting for loops?
234 9 • Lists
TRY IT
Matrix multiplication
Write a program that calculates the matrix multiplication product of the matrices matW and matZ below
and prints the result. The expected result is shown.
In the result matrix, each element is calculated according to the position of the element. The result at
position [i][j] is calculated using row i from the first matrix, W, and column j from the second matrix, Z.
Ex:
List comprehensions
A list comprehension is a Python statement to compactly create a new list using a pattern.
list_name refers to the name of a new list, which can be anything, and the for is the for loop keyword. An
expression defines what will become part of the new list. loop_variable is an iterator, and iterable is an
object that can be iterated, such as a list or string.
EXAMPLE 9.5
EXAMPLE 9.6
one fish
two fish
red fish
blue fish
CONCEPTS IN PRACTICE
List comprehensions
1. The component of a list comprehension defining an element of the new list is the _____.
a. expression
b. loop_variable
c. container
2. What would be the contents of b_list after executing the code below?
a_list = [1, 2, 3, 4, 5]
b_list = [i+2 for i in a_list]
a. [1, 2, 3, 4, 5]
b. [0, 1, 2, 3, 4]
c. [3, 4, 5, 6, 7]
In a filter list comprehension, an element is added into list_name only if the condition is met.
CHECKPOINT
Filtering a list
Access multimedia content ([Link]
comprehensions)
CONCEPTS IN PRACTICE
a. [i, i, a, o, e]
b. ['i', 'i'', 'a', 'o', 'e']
c. Error
a. []
b. [21]
c. [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
TRY IT
TRY IT
• Lists are mutable and can be easily modified by using append(), remove(), and pop() operations.
• Lists are iterable and can be iterated using an iterator or element indexes.
• The sort() operation arranges the elements of a list in ascending order if all elements of the list are of
the same type.
• The reverse() operation reverses a list.
• The copy() method is used to create a copy of a list.
• Lists have built-in functions for finding the maximum, minimum, and summation of a list for lists with only
numeric values.
• Lists can be nested to represent multidimensional data.
• A list comprehension is a compact way of creating a new list, which can be used to filter items from an
existing list.
Function Description
remove(element) Removes the specified element from the list if the element exists.
Function Description
Since strings are immutable in Python, to replace a substring, a new string must be created using slicing and concatenation. For example, to replace 'hello' with 'Hi' in 'Hello my fellow classmates', we create a new string as 'Hi' + original[5:]. Lists, in contrast, are mutable, allowing direct modifications without the need to create a new object .
In Python, positive indexing starts from 0 at the beginning of the string, with 0 being the first character. Negative indexing starts from -1 at the end of the string. For example, in the string "hello", the character at index 1 (positive) is 'e', and the character at index -2 (negative) in "Blue" is 'u' .
List comprehensions in Python are more concise and usually faster than traditional for loops for creating lists because they allow filtering and transformations in a single line of code. For example, to create a list of squares up to 9, a list comprehension would be: [i*i for i in range(10)], generating [0, 1, 4, 9, 16, 25, 36, 49, 64, 81].
Nested loops in Python can iterate over a list of lists by using an outer loop for rows and an inner loop for columns. For example, given list1 = [[1, 2, 3], [1, 4, 9], [1, 8, 27]], using nested loops prints each number row by row: '1 2 3', '1 4 9', '1 8 27' .
In Python, strings are immutable, meaning once a string is created, its content cannot be altered directly. For example, to modify a string, a new string must be created. If we have x = "string", changing the first character could be achieved by: x = '*' + x[1:], resulting in '*tring' .
The lower() and upper() methods in Python do not modify the original string; instead, they return a new string where all characters are converted to lowercase or uppercase, respectively. For the string "aBbA", lower() would return "abba" and upper() would return "ABBA" .
The count() method in Python returns the number of occurrences of a substring within a string. For the string "banana", using count('an') calculates the occurrences of 'an', which appears once, thus the method returns 1 .
The 'in' operator in Python checks if a substring is present within another string, returning True if it is found and False otherwise. For the string 'an umbrella', 'a' is present multiple times, so the result is True .
Sorting a list of strings in dictionary order using Python's sort() method arranges the elements alphabetically based on their ASCII values. This is significant for tasks requiring lexicographical order, such as organizing words alphabetically or preparing data for binary search. For example, sorting ['banana', 'apple', 'cherry'] results in ['apple', 'banana', 'cherry'].
String slicing in Python involves retrieving a portion of a string using a substring operator [a:b], which returns characters from index a (inclusive) to b (exclusive). For "Hello world", slicing with [2:4] extracts 'll' .