0% found this document useful (0 votes)
15 views51 pages

Overview of Python Built-in Modules

The document discusses Python's built-in and third-party modules, highlighting the extensive collection available in the Python Standard Library and the Python Package Index (PyPI). It provides examples of built-in modules like math and datetime, as well as third-party modules such as numpy and requests, emphasizing their utility for various programming tasks. Additionally, it outlines the philosophy of Python's 'batteries included' approach, ensuring that most programming needs are met through these libraries.

Uploaded by

blutonium.in
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views51 pages

Overview of Python Built-in Modules

The document discusses Python's built-in and third-party modules, highlighting the extensive collection available in the Python Standard Library and the Python Package Index (PyPI). It provides examples of built-in modules like math and datetime, as well as third-party modules such as numpy and requests, emphasizing their utility for various programming tasks. Additionally, it outlines the philosophy of Python's 'batteries included' approach, ensuring that most programming needs are met through these libraries.

Uploaded by

blutonium.in
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

190 7 • 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.

For decades, Python has maintained a "batteries included ([Link] philosophy.


This philosophy means that the standard library should come with everything most programmers need. In
fact, the standard library includes over 200 built-in modules!

Module Description

calendar General calendar-related functions.

datetime Basic date and time types and functions.

email Generate and process email messages.

math Mathematical functions and constants.

os Interact with the operating system.

random Generate pseudo-random numbers.

statistics Mathematical statistics functions.

sys System-specific parameters and functions.

turtle Educational framework for simple graphics.

zipfile Read and write ZIP-format archive files.

Table 7.1 Example built-in modules in the standard library.

CONCEPTS IN PRACTICE

Built-in modules
Use the library reference, module index, and documentation links above to answer the questions.

1. Which page provides a list of built-in modules sorted by category?


a. library reference
b. module index
c. PEP 2

Access for free at [Link]


7.5 • Finding modules 191

2. What is the value of [Link]?


a. 1
b. 6
c. 7

3. Which built-in module enables the development of graphical user interfaces?


a. tkinter
b. turtle
c. webbrowser

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

arrow Convert and format dates, times, and timestamps.

BeautifulSoup Extract data from HTML and XML documents.

bokeh Interactive plots and applications in the browser.

matplotlib Static, animated, and interactive visualizations.

moviepy Video editing, compositing, and processing.

nltk Natural language toolkit for human languages.

numpy Fundamental package for numerical computing.

pandas Data analysis, time series, and statistics library.

pillow Image processing for jpg, png, and other formats.

Table 7.2 Example third-party modules available from PyPI.


192 7 • Modules

Module Description

pytest Full-featured testing tool and unit test framework.

requests Elegant HTTP library for connecting to web servers.

scikit-learn Simple, efficient tools for predictive data analysis.

scipy Fundamental algorithms for scientific computing.

scrapy Crawl websites and scrape data from web pages.

tensorflow End-to-end machine learning platform for everyone.

Table 7.2 Example third-party modules available from PyPI.

CONCEPTS IN PRACTICE

Third-party modules
Use [Link] and the links in the table above to answer the questions.

4. Which modules can be used to edit pictures and videos?


a. BeautifulSoup and Scrapy
b. Bokeh and Matplotlib
c. MoviePy and Pillow

5. Which third-party module is a replacement for the built-in datetime module?


a. arrow
b. calendar
c. time

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.

• Top 20 Python Libraries for Data Science for 2023 ([Link]


• 24 Best Python Libraries You Should Check in 2022 ([Link]

Access for free at [Link]


7.5 • Finding modules 193

• Most Popular Python Packages in 2021 ([Link]

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:

• Examples of Usage: date ([Link]


• Examples of Usage: timedelta ([Link]

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:

Your birth date: 2005-03-14


Today's date is: 2023-06-01

You were born 6653 days ago


(that is 574819200 seconds)

You are about 18 years old

Access multimedia content ([Link]


7-5-finding-modules)

TRY IT

More exact age


The datetime module does not provide a built-in way to display a person's exact age. Ex: The following
program calculates an exact age (in years and days) using floor division and modulo. The output is: You
are 15 years and 4 days old.

from datetime import date

birth = date(2005, 3, 14)


today = date(2020, 3, 14) # 15 years later
delta = today - birth

years = [Link] // 365


days = [Link] % 365
print("You are", years, "years and", days, "days old")
194 7 • Modules

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]()

Refer to the humanize() ([Link] examples from the arrow module


documentation. In the Python shell, figure out how to display the number of years and days since birth
using one line of code. Then display the number of years, months, and days since birth. Finally, use the
print() function to output the results in this format: You are 18 years 4 months and 7 days old.

As time permits, experiment with other functions provided by the arrow module.

7.6 Chapter summary


Highlights from this chapter include:

• 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

import module Imports a module for use in another program.

from module import


function Imports a specific function from a module.

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).

Table 7.3 Chapter 7 reference.

Access for free at [Link]


7.6 • Chapter summary 195

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.

help(function_name) Shows the docstring for the given function.

Creates a date object representing February 14, 2023.


date(2023, 2, 14)
Requires: from datetime import date.

Table 7.3 Chapter 7 reference.


196 7 • Modules

Access for free at [Link]


8
Strings

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.

8.1 String operations


Learning objectives
By the end of this section you should be able to

• Compare strings using logical and membership operators.


• Use lower() and upper() string methods to convert string values to lowercase and uppercase
characters.

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

Operator Description Example Output Explanation

Checks whether the When comparing "c" operand to "d"


first string value is operand, the ASCII value for "c" is smaller
"c" >
> or >= greater than (or greater False than the ASCII value for "d". Therefore, "c"
"d"
than or equal to) the < "d". The expression "c" > "d"
second string value. evaluates to False.

Checks whether the When comparing "ab" operand to "ac"


first string value is less operand, the first characters are the same,
"ab" <
< or <= than (or less than or True but the second character of "ab" is less
"ac"
equal to) the second than the second character in "ac" and as
string value. such "ab" < "ac".

"aa" == Since all characters in the first operand and


== Checks whether two True
"aa" the second operand are the same, the two
string values are equal.
string values are equal.

The two operands contain different string


Checks whether two "a" != values ("a" vs. "b"), and the result of
!= string values are not True
"b" checking whether the two are not the same
equal. evaluates to True.

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.

Table 8.1 Comparing string values.

CONCEPTS IN PRACTICE

Using logical and membership operators to compare string values


1. What is the output of ("aaa" < "aab")?
a. True
b. False

2. What is the output of ("aa" < "a")?


a. True
b. False

Access for free at [Link]


8.1 • String operations 199

3. What is the output of ("aples" in "apples")?


a. undefined
b. True
c. False

lower() and upper()


Python has many useful methods for modifying strings, two of which are lower() and upper() methods. The
lower() method returns the converted alphabetical characters to lowercase, and the upper() method returns
the converted alphabetical characters to uppercase. Both the lower() and upper() methods do not modify
the string.

EXAMPLE 8.1

Converting characters in a string


In the example below, the lower() and upper() string methods are called on the string variable x to
convert all characters to lowercase and uppercase, respectively.

x = "Apples"

# The lower() method converts a string to all lowercase characters


print([Link]())

# The upper() method converts a string to all uppercase characters


print([Link]())

The above code's output is:

apples
APPLES

CONCEPTS IN PRACTICE

Using lower() and upper()


4. What is the output of "aBbA".lower()?
a. abba
b. ABBA
c. abbA

5. What is the output of "aBbA".upper()?


a. abba
200 8 • Strings

b. ABBA
c. ABbA
d. aBBA

6. What is the output of ("a".upper() == "A")?


a. True
b. False

TRY IT

Number of characters in the string


A string variable, s_input, is defined. Use lower() and upper() to convert the string to lowercase and
uppercase, and print the results in the output. Also, print the number of characters in the string, including
space characters.

Access multimedia content ([Link]


8-1-string-operations)

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".

Access multimedia content ([Link]


8-1-string-operations)

8.2 String slicing


Learning objectives
By the end of this section you should be able to

• Use string indexing to access characters in the string.


• Use string slicing to get a substring from a string.
• Identify immutability characteristics of strings.

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.

Access for free at [Link]


8.2 • String slicing 201

CHECKPOINT

String indexing
Access multimedia content ([Link]
8-2-string-slicing)

CONCEPTS IN PRACTICE

Accessing characters in a string using indexing


1. Which character is at index 1 in the string "hello"?
a. "h"
b. "e"
c. "o"

2. What is the character at index -2 in the string "Blue"?


a. "e"
b. "u"
c. "l"

3. What is the output of the following code?

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

Getting the minutes


Consider a time value is given as "hh:mm" with "hh" representing the hour and "mm" representing the
minutes. To retrieve only the string's minutes portion, the following code can be used:

time_string = "13:46"
minutes = time_string[3:5]
print(minutes)
202 8 • Strings

The above code's output is:

46

EXAMPLE 8.3

Getting the hour


Consider a time value is given as "hh:mm" with "hh" representing the hour and "mm" representing the
minutes. To retrieve only the string's hour portion, the following code can be used:

time_string = "14:50"
hour = time_string[:2]
print(hour)

The above code's output is:

14

CONCEPTS IN PRACTICE

Getting a substring using string slicing


4. What is the output of the following code?

a_string = "Hello world"


print(a_string[2:4])

a. "el"
b. "ll"
c. "llo"

5. What is the output of the following code?

location = "classroom"
print(location[-3:-1])

a. "ro"
b. "oo"
c. "oom"

6. What is the output of the following code?

Access for free at [Link]


8.2 • String slicing 203

greeting = "hi Leila"


name = greeting[3:]

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

Strings are immutable


Access multimedia content ([Link]
8-2-string-slicing)

CONCEPTS IN PRACTICE

Modifying string content


7. What is the correct way of replacing the first character in a string to character "*" in a new string?
a. x = "string"
x[0] = "*"
b. x = "string"
x = "*" + x[1:]
c. x = "string"
x = "*" + x

8. What type of error will result from the following code?

string_variable = "example"
string_variable[-1] = ""

a. TypeError
b. IndexError
c. NameError

9. What is the output of the following code?

str = "morning"
str = str[1]
print(str)
204 8 • Strings

a. TypeError
b. m
c. o

TRY IT

Changing the greeting message


Given the string "Hello my fellow classmates" containing a greeting message, print the first word by
getting the beginning of the string up to (and including) the 5th character. Change the first word in the
string to "Hi" instead of "hello" and print the greeting message again.

Access multimedia content ([Link]


8-2-string-slicing)

TRY IT

Editing the string at specified locations


Given a string variable, string_variable, and a list of indexes, remove characters at the specified indexes
and print the resulting string.

Input:
string_variable = "great"
indices = [0, 1]

prints eat

Access multimedia content ([Link]


8-2-string-slicing)

8.3 Searching/testing strings


Learning objectives
By the end of this section you should be able to

• Use the in operator to identify whether a given string contains a substring.


• Call the count() method to count the number of substrings in a given string.
• Search a string to find a substring using the find() method.
• Use the index() method to find the index of the first occurrence of a substring in a given string.
• Write a for loop on strings using in operator.

Access for free at [Link]


8.3 • Searching/testing strings 205

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

What is in the phrase?


Access multimedia content ([Link]
8-3-searchingtesting-strings)

CONCEPTS IN PRACTICE

Using in operator to find substrings


1. What is the output of ("a" in "an umbrella")?
a. 2
b. False
c. True
d. 1

2. What is the output of ("ab" in "arbitrary")?


a. True
b. False

3. What is the output of ("" in "string")?


a. True
b. False

For loop using in operator


The in operator can be used to iterate over characters in a string using a for loop. In each for loop iteration,
one character is read and will be the loop variable for that iteration.

CHECKPOINT

for loop using in operator


Access multimedia content ([Link]
8-3-searchingtesting-strings)

CONCEPTS IN PRACTICE

Using in operator within for loop


4. What is the output of the following code?
206 8 • Strings

for c in "string":
print(c, end = "")

a. string
b. s
t
r
i
n
g
c. s t r i n g

5. What is the output of the following code?

count = 0
for c in "abca":
if c == "a":
count += 1
print(count)

a. 0
b. 1
c. 2

6. What is the output of the following code?

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.

Access for free at [Link]


8.3 • Searching/testing strings 207

CHECKPOINT

Counting the number of occurrences of a substring


Access multimedia content ([Link]
8-3-searchingtesting-strings)

CONCEPTS IN PRACTICE

Using count() to count the number of substrings


7. What is the output of (aaa".count("a"))?
a. True
b. 1
c. 3

8. What is the output of ("weather".count("b"))?


a. 0
b. -1
c. False

9. What is the output of ("aaa".count("aa"))?


a. 1
b. 2
c. 3

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

Finding the first index of a substring


Access multimedia content ([Link]
8-3-searchingtesting-strings)

CONCEPTS IN PRACTICE

Using find() to locate a substring


10. What is the output of "banana".find("a")?
a. 1
b. 3
c. 5

11. What is the output of "banana".find("c")?


208 8 • Strings

a. 0
b. -1
c. ValueError

12. What is the output of "b".find("banana")?


a. -1
b. 0
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

Getting the time's minute portion


Consider a time value is given as part of a string using the format of "hh:mm" with "hh" representing the
hour and "mm" representing the minutes. To retrieve only the string's minute portion, the following code
can be used:

time_string = "The time is 12:50"


index = time_string.index(":")
print(time_string[index+1:index+3])

The above code's output is:

50

CONCEPTS IN PRACTICE

Using index() to locate a substring


13. What is the output of "school".index("o")?
a. 3
b. 4
c. -3

14. What is the output of "school".index("ooo")?


a. 3
b. 4

Access for free at [Link]


8.4 • String formatting 209

c. ValueError

15. What is the output of the following code?

sentence = "This is a sentence"


index = [Link](" ")
print(sentence[:index])

a. "This"
b. "This "
c. "sentence"

TRY IT

Finding all spaces


Write a program that, given a string, counts the number of space characters in the string. Also, print the
given string with all spaces removed.

Input: "This is great"

prints:
2
Thisisgreat

Access multimedia content ([Link]


8-3-searchingtesting-strings)

8.4 String formatting


Learning objectives
By the end of this section you should be able to

• Format a string template using input arguments.


• Use format() to generate numerical formats based on a given template.

String format specification


Python provides string substitutions syntax for formatting strings with input arguments. Formatting string
includes specifying string pattern rules and modifying the string according to the formatting specification.
Examples of formatting strings include using patterns for building different string values and specifying
modification rules for the string's length and alignment.

String formatting with replacement fields


Replacement fields are used to define a pattern for creating multiple string values that comply with a given
210 8 • Strings

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

String values from the same template

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

String template formatting for course enrollment requests


A string template with replacement fields is defined below to create string values with different input
arguments. The format() method is used to pass inputs to the template in the same order.

s = "Dear {}, I'd like to take a {} course with Prof. {}."

print(s)
print([Link]("John", "programming", "Potter"))
print([Link]("Kishwar", "math", "Robinson"))

The above code's output is:

Dear {}, I'd like to take a {} course with Prof. {}.


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.

CONCEPTS IN PRACTICE

String template and formatting


1. What is the output of print("Hello {}!".format("Ana"))?
a. Ana

Access for free at [Link]


8.4 • String formatting 211

b. Hello Ana
c. Hello Ana!

2. What is the output of print("{}:{}".format("One", "1"))?


a. One1
b. One:1
c. 1:One

3. What is the output of print("{}".format("one", "two", "three"))?


a. one
b. two
c. onetwothree

Named replacement fields


Replacement fields can be tagged with a label, called named replacement fields, for ease of access and code
readability. The example below illustrates how named replacement fields can be used in string templates.

EXAMPLE 8.7

Season weather template using named replacement fields


A named replacement argument is a convenient way of assigning name tags to replacement fields and
passing values associated with replacement fields using corresponding names (instead of passing values in
order).

s = "Weather in {season} is {temperature}."

print(s)
print([Link](season = "summer", temperature = "hot"))
print([Link](season = "winter", temperature = "cold"))

The above code's output is:

Weather in {season} is {temperature}.


Weather in summer is hot.
Weather in winter is cold.

MULTIPLE USE OF A NAMED ARGUMENT

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

s = "Weather in {season} is {temperature}; very very {temperature}."

print(s)
print([Link](season = "summer", temperature = "hot"))
print([Link](temperature = "cold", season = "winter"))

The above code's output is:

Weather in {season} is {temperature}; very very {temperature}.


Weather in summer is hot; very very hot.
Weather in winter is cold; very very cold.

CONCEPTS IN PRACTICE

Named replacement field examples


4. What is the output of print("Hey {name}!".format(name = "Bengio"))?
a. Hey name!
b. Hey Bengio
c. Hey Bengio!

5. What is the output of print("Hey {name}!".format("Bengio"))?


a. Hey name!
b. KeyError
c. Hey Bengio!

6. What is the output of the following code?

greeting = "Hi"
name = "Jess"
print("{greeting} {name}".format(greeting = greeting, name = name))

a. greeting name
b. Hi Jess
c. Jess Hi

Numbered replacement fields


Python's string format() method can use positional ordering to match the numbered arguments. The
replacement fields that use the positional ordering of arguments are called numbered replacement fields.
The indexing of the arguments starts from 0. Ex: print("{1}{0}".format("Home", "Welcome")) outputs
the string value "Welcome Home" as the first argument. "Home" is at index 0, and the second argument,
"Welcome", is at index 1. Replacing these arguments in the order of "{1}{0}" creates the string "Welcome

Access for free at [Link]


8.4 • String formatting 213

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

Numbered replacement field to build a phrase


Numbered replacement fields are used in this example to build phrases like "very very cold" or "very
hot".

template1 = "{0} {0} {1}"


template2 = "{0} {1}"

print([Link]("very", "cold"))
print([Link]("very", "hot"))

The above code's output is:

very very cold


very hot

String length and alignment formatting


Formatting the string length may be needed for standardizing the output style when multiple string values of
the same context are being created and printed. The example below shows a use case of string formatting in
printing a table with minimum-length columns and specific alignment.

EXAMPLE 8.9

A formatted table of a class roster


A formatted table of a class roster

Student Name Major Grade


----------------------------------------------
Manoj Sara Computer Science A-
Gabriel Wang Electrical Engineering A
Alex Narayanan Social Sciences A+

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"))

Table 8.2 String alignment formatting.

CONCEPTS IN PRACTICE

Specifying field width and alignment


7. What is the output of the following code?

template = "{name:12}"
formatted_name = [Link](name = "Alice")
print(len(formatted_name))

a. 5
b. 12
c. "Alice"

8. What is the output of the following code?

Access for free at [Link]


8.4 • String formatting 215

template = "{greeting:>6}"
formatted_greeting = [Link](greeting = "Hello")
print(formatted_greeting[0])

a. H
b. " Hello"
c. Space character

9. What is the output of the following code?

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 index field refers to the index of the argument.


• The width field refers to the minimum length of the string.
• The precision field refers to the floating-point precision of the given number.
• The type field shows the type of the input that is passed to the format() method. Floating-point and
decimal inputs are identified by "f" and "d", respectively. String values are also identified by "s".

The table below summarizes formatting options for modifying numeric values.

Example Output Explanation

The format specification .7 shows the output


must have seven decimal places. The f
print("{:.7f}".format(0.9795)) 0.9795000
specification is an identifier of floating-point
formatting.

The format specification .3 shows the output


must have three decimal places. The f
print("{:.3f}".format(12)) 12.000
specification is an identifier of floating-point
formatting.

Table 8.3 Numerical formatting options.


216 8 • Strings

Example Output Explanation

The format specification .2 shows the output


must have two decimal places. The f specification
print("{:+.2f}".format(4)) +4.00 is an identifier of floating-point formatting. The +
sign before the precision specification adds a sign
character to the output.

The format specification 0>5 defines the width


field as 5, and thus the output must have a
minimum length of 5. And, if the number has
print("{:0>5d}".format(5)) 00005 fewer than five digits, the number must be
padded with 0's from the left side. The d
specification is an identifier of a decimal number
formatting.

The format specification .3 shows the output will


print("{:.3s}".format("12.50")) 12. have three characters. The s specification is an
identifier of string formatting.

Table 8.3 Numerical formatting options.

CONCEPTS IN PRACTICE

Numeric value formatting examples


10. What is the output of print('{0:.3f}'.format(3.141592))?
a. 3.141592
b. 3.1
c. 3.142

11. What is the output of print('{:1>3d}'.format(3))?


a. 113
b. 311
c. 3.000

12. What is the output of print('{:+d}'.format(123))?


a. 123
b. +123
c. :+123

Access for free at [Link]


8.5 • Splitting/joining strings 217

TRY IT

Formatting a list of numbers


Given a list of numbers (floating-point or integer), print numbers with two decimal place precision and at
least six characters.

Input: [12.5, 2]

Prints: 012.50

002:00

Access multimedia content ([Link]


8-4-string-formatting)

8.5 Splitting/joining strings


Learning objectives
By the end of this section you should be able to

• Use the split() method to split a string into substrings.


• Combine objects in a list into a string using join() method.

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

split() for breaking down the string into tokens


Access multimedia content ([Link]
8-5-splittingjoining-strings)

CONCEPTS IN PRACTICE

Examples of string delimiters and split() method


1. What is the output of print("1*2*3*".split('*'))?
a. ["1", "*", "2", "*", "3", "*"]
218 8 • Strings

b. ["1", "2', "3"]


c. [1, 2, 3]

2. What is the output of print("a year includes 12 months".split())?


a. ["a year includes 12 months"]
b. ["a", "year", "includes", 12, "months"]
c. ["a", "year", "includes", "12", "months"]

3. What is the output of the following code?

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

join() for combining tokens into one string


Access multimedia content ([Link]
8-5-splittingjoining-strings)

CONCEPTS IN PRACTICE

Applying join() method on list of string values


4. What is the output of the following code?

elements = ['A', 'beautiful', 'day', 'for', 'learning']

print(",".join(elements))

a. 'A beautiful day for learning'


b. ['A, beautiful, day, for, learning']
c. 'A,beautiful,day,for,learning'

5. What is the length of the string "sss".join(["1","2"])?


a. 2

Access for free at [Link]


8.5 • Splitting/joining strings 219

b. 5
c. 8

6. What is the value stored in the variable out?

s = ["1", "2"]
out = "".join(s)

a. 12
b. "12"
c. "1 2"

TRY IT

Unique and comma-separated words


Write a program that accepts a comma-separated sequence of words as input, and prints words in separate
lines. Ex: Given the string "happy,smiling,face", the output would be:

happy
smiling
face

Access multimedia content ([Link]


8-5-splittingjoining-strings)

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:

• If the user inputs nothing, the program outputs:


You ordered nothing.
• If the user inputs one item (Ex: eggs), the program outputs:
You ordered eggs.
• If the user inputs two items (Ex: eggs, ham), the program outputs:
You ordered eggs and ham.
• If the user inputs three or more items (Ex: eggs, ham, toast), the program outputs:
You ordered eggs, ham, and toast.

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.

Access multimedia content ([Link]


220 8 • Strings

8-5-splittingjoining-strings)

8.6 Chapter summary


Highlights from this chapter include:

• A string is a sequence of characters.


• Logical operators can be used to compare two string values. String comparison is done by comparing
corresponding ASCII values of characters in the order of appearance in the string.
• String indexing is used to access a character or a sequence of characters in the string.
• String objects are immutable.
• String splicing.

At this point, you should be able to write programs dealing with string values.

Method Description

len() Returns the string length.

upper() Returns uppercase characters.

lower() Returns lowercase characters.

count() Returns the number of a given substring in a string.

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.

format() Used to create strings with specified patterns using arguments.

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

Table 8.4 Chapter 8 reference.

Access for free at [Link]


8.6 • Chapter summary 221

Method Description

in Checks if a substring exists in a string.

in operator in for character in string:


a for loop # loop body

Table 8.4 Chapter 8 reference.


222 8 • Strings

Access for free at [Link]


9
Lists

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.

9.1 Modifying and iterating lists


Learning objectives
By the end of this section you should be able to

• Modify a list using append(), remove(), and pop() list operations.


• Search a list using a for loop.

Using list operations to modify a list


An append() operation is used to add an element to the end of a list. In programming, append means add to
the end. A remove() operation removes the specified element from a list. A pop() operation removes the last
item of a list.
224 9 • Lists

EXAMPLE 9.1

Simple operations to modify a list


The code below demonstrates simple operations for modifying a list.

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.

1 """Operations for adding and removing elements from a list."""


2
3 # Create a list of students working on a project
4 student_list = ["Jamie", "Vicky", "DeShawn", "Tae"]
5 print(student_list)
6
7 # Another student joins the project. The student must be added
to the list.
8 student_list.append("Ming")
9 print(student_list)
10
11 # "Jamie" withdraws from the project. Jamie must be removed
from the list.
12 student_list.remove("Jamie")
13 print(student_list)
14
15 # Suppose "Ming" had to be removed from the list.
16 # A pop() operation can be used since Ming is last in the
list.
17 student_list.pop()
18 print(student_list)

The above code's output is:

['Jamie', 'Vicky', 'DeShawn', 'Tae']


['Jamie', 'Vicky', 'DeShawn', 'Tae', 'Ming']
['Vicky', 'DeShawn', 'Tae', 'Ming']
['Vicky', 'DeShawn', 'Tae']

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()

Access for free at [Link]


9.1 • Modifying and iterating lists 225

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

Using len() to get the length of a list


Access multimedia content ([Link]
9-1-modifying-and-iterating-lists)

CONCEPTS IN PRACTICE

Iterating lists
For the following questions, consider the list:

my_list = [2, 3, 5, 7, 9]

4. How many times will the following for loop execute?


for element in my_list:
a. 5
b. 4

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

6. What is the output of the code below?

for i in range(0, len(my_list), 2):


print(my_list[i], end=' ')

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, add volleyball to the list.

Next, remove "football" from the list and add "soccer" to the list.

Show the list contents after each modification.

Access multimedia content ([Link]


9-1-modifying-and-iterating-lists)

TRY IT

Simple Searching
Write a program that prints "found!" if "soccer" is found in the given list.

Access multimedia content ([Link]


9-1-modifying-and-iterating-lists)

9.2 Sorting and reversing lists


Learning objectives
By the end of this section you should be able to

• Understand the concept of sorting.


• Use built-in sort() and reverse() methods.

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]

Access for free at [Link]


9.2 • Sorting and reversing lists 227

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

2. Arrange the following list in ascending order.


["cat", "bat", "dog", "coyote", "wolf"]
a. ["bat", "cat", "coyote", "dog", "wolf"]
b. ["wolf", "coyote", "dog", "cat", "bat"]

3. How are the words "flask" and "flash" related in Python?


a. "flask" < "flash"
b. "flask" == "flash"
c. "flask" > "flash"

Using sort() and reverse()


Python provides methods for arranging elements in a list.

• 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

Sorting and reversing lists

# Setup a list of numbers


num_list = [38, 92, 23, 16]
print(num_list)

# Sort the list


num_list.sort()
print(num_list)

# Setup a list of words


dance_list = ["Stepping", "Ballet", "Salsa", "Kathak", "Hopak", "Flamenco",
"Dabke"]
228 9 • Lists

# Reverse the list


dance_list.reverse()
print(dance_list)

# Sort the list


dance_list.sort()
print(dance_list)

The above code's output is:

[38, 92, 23, 16]


[16, 23, 38, 92]
["Dabke", "Flamenco", "Hopak", "Kathak", "Salsa", "Ballet", "Stepping"]
["Ballet", "Dabke", "Flamenco", "Hopak", "Kathak", "Salsa", "Stepping"]

CONCEPTS IN PRACTICE

sort() and reverse() methods


Use the following list for the questions below.

board_games = ["go", "chess", "scrabble", "checkers"]

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')

5. What is the correct way to reverse the list board_games?


a. board_games.reverse()
b. reverse(board_games)

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

Sorting and reversing


Complete the program below to arrange and print the numbers in ascending and descending order.

Access for free at [Link]


9.3 • Common list operations 229

Access multimedia content ([Link]


9-2-sorting-and-reversing-lists)

9.3 Common list operations


Learning objectives
By the end of this section you should be able to

• Use built-in functions max(), min(), and sum().


• Demonstrate how to copy a list.

Using built-in operations


The max() function called on a list returns the largest element in the list. The min() function called on a list
returns the smallest element in the list. The max() and min() functions work for lists as long as elements
within the list are comparable.

The sum() function called on a list of numbers returns the sum of all elements in the list.

EXAMPLE 9.3

Common list operations

"""Common list operations."""

# Set up a list of number


snum_list = [28, 92, 17, 3, -5, 999, 1]

# Set up a list of words


city_list = ["New York", "Missoula", "Chicago", "Bozeman",
"Birmingham", "Austin", "Sacramento"]

# Usage of the max() funtion


print(max(num_list))

# max() function works for strings as well


print(max(city_list))

# Usage of the min() funtion which also works for strings


print(min(num_list))

print(min(city_list))

# sum() only works for a list of numbers


print(sum(num_list))

The above code's output is:


230 9 • Lists

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)

2. What is the minimum of the following list?


["Lollapalooza", "Coachella", "Newport Jazz festival", "Hardly Strictly
Bluegrass", "Austin City Limits"]
a. Coachella
b. Austin City Limits
c. The minimum doesn't exist.

3. What value does the function call return?


sum([1.2, 2.1, 3.2, 5.9])
a. sum() only works for integers.
b. 11
c. 12.4

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?

Access for free at [Link]


9.4 • Nested lists 231

my_list = [1, 2, 3]
list2 = my_list
list2[0] = 13
print(sum(my_list))

a. 6
b. 13
c. 18

5. What is the output of the following code?

my_list = [1, 2, 3]
list2 = my_list.copy()
list2[0] = 13
print(max(my_list))

a. 3
b. 13
c. 18

6. What is the output of the following code?

my_list = ["Cat", "Dog", "Hamster"]


list2 = my_list
list2[2] = "Pigeon"
print(sum(my_list))

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).

Access multimedia content ([Link]


9-3-common-list-operations)

9.4 Nested lists


Learning objectives
By the end of this section you should be able to

• Demonstrate the use of a list-of-lists to structure data.


• Demonstrate individual element addressing using multi-dimensional indexing.
• Use nested loops to iterate a list-of-lists.
232 9 • Lists

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:

1. What would be the correct way to represent matA in Python?


a. [[7, 4, 5], [3, 9, 6], [1, 2, 8]]
b. [7, 4, 5
3, 9, 6
1, 2, 8]
c. [[7, 3, 1], [4, 9, 2], [1, 2, 8]

2. What would be the correct index for the number 6 in the above list?
a. [5]
b. [2][1]
c. [1][2]

3. What would be the result of the following code:

print(matA[0])

a. Error
b. 7
c. [7, 4, 5]

Using nested loops to iterate nested lists


A nested loop structure can be used to iterate a list-of-lists. For a two-dimensional list-of-lists, an outer for
loop can be used for rows, and an inner for loop can be used for columns.

Access for free at [Link]


9.4 • Nested lists 233

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()

The above code's output is:

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:

my_list = [[7, 4, 5, 12],


[24, 3, 9, 16],
[12, 8, 91, -5]]

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

a. for column_index in range(0, len(my_list[0])):


for row_index in range (0, len(my_list)):
print(my_list[row_index][column_index])
b. for row_index in range(0, len(my_list)):
for column_index in range (0, len(my_list)):
print(my_list[row_index][column_index])
print()
c. for row_index in range(0, len(my_list)):
for column_index in range (0, len(my_list[0])):
print(my_list[row_index][column_index])

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:

result[1][2] = (row 1 in W) times (column 2 in Z)

Access multimedia content ([Link]


9-4-nested-lists)

9.5 List comprehensions


Learning objectives
By the end of this section you should be able to

• Identify the different components of a list comprehension statement.


• Implement filtering using list comprehension.

Access for free at [Link]


9.5 • List comprehensions 235

List comprehensions
A list comprehension is a Python statement to compactly create a new list using a pattern.

The general form of a list comprehension statement is shown below.

list_name = [expression for loop_variable in iterable]

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

Creating a new list with a list comprehension


A list comprehension shown below in the second code has the same effect as the regular for loop shown in
the first code. The resultant list is [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] in both cases.

Creating a list of squares using a for loop.

# Create an empty List.


squares_list = []

# Add items to a list, as squares of numbers starting at 0 and ending at 9.


for i in range(10):
squares_list.append(i*i)

Creating a list of squares using the list comprehension.

square_list = [i*i for i in range(10)]

The expression i*i is applied for each value of the loop_variable i.

EXAMPLE 9.6

A Dr. Seuss poem


A list comprehension can be used to create a list based on another list. In line 6, the for loop is written on
the list poem_lines.

1 # Create a list of words


2 words_list = ["one", "two", "red", "blue"]
3
4 # Use a list comprehension to create a new list called
poem_lines
5 # Inserting the word "fish" attached to each word in words_list
6 poem_lines = [w + " fish" for w in words_list]
236 9 • Lists

7 for line in poem_lines:


8 print(line)

The above code's output is:

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]

3. What does new_list contain after executing the statement below?

new_list = [i//3 for i in range(1, 15, 3)]

a. [0.3333333333333333, 1.3333333333333333, 2.3333333333333335,


3.3333333333333335, 4.333333333333333]
b. [0, 1, 2, 3, 4]
c. [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]

Filtering using list comprehensions


List comprehensions can be used to filter items from a given list. A condition is added to the list
comprehension.

list_name = [expression for loop_variable in container if condition]

In a filter list comprehension, an element is added into list_name only if the condition is met.

Access for free at [Link]


9.5 • List comprehensions 237

CHECKPOINT

Filtering a list
Access multimedia content ([Link]
comprehensions)

CONCEPTS IN PRACTICE

Filtering using list comprehensions


For each code using list comprehension, select the correct resultant list in new_list.

4. my_list = [21, -1, 50, -9, 300, -50, 2]

new_list = [m for m in my_list if m < 0]

a. [21, 50, 300, 2]


b. [21, -1, 50, -9, 300, -50, 2]
c. [-1, -9, -50]

5. my_string = "This is a home."

new_list = [i for i in my_string if i in 'aeiou']

a. [i, i, a, o, e]
b. ['i', 'i'', 'a', 'o', 'e']
c. Error

6. new_list = [r for r in range (0, 21, 2) if r%2 != 0]

a. []
b. [21]
c. [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

TRY IT

Selecting five-letter words


Write a program that creates a list of only five-letter words from the given list and prints the new list.

Access multimedia content ([Link]


comprehensions)
238 9 • Lists

TRY IT

Books starting with "A"


Write a program that selects words that begin with an "A" in the given list. Make sure the new list is then
sorted in dictionary order. Finally, print the new sorted list.

Access multimedia content ([Link]


comprehensions)

9.6 Chapter summary


Highlights from this chapter include:

• 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.

At this point, you should be able to write programs using lists.

Function Description

append(element) Adds the specified element to the end of a list.

remove(element) Removes the specified element from the list if the element exists.

pop() Removes the last element of a list.

max(list) Returns the maximum element of the list specified.

min(list) Returns the maximum element of the list specified.

sum(list) Returns the summation of a list composed of numbers.

sort() Sorts a list on which the method is called in ascending order.

Table 9.1 Chapter 9 reference.

Access for free at [Link]


9.6 • Chapter summary 239

Function Description

reverse() Reverses the order of elements in a list.

copy() Makes a complete copy of a list.

Table 9.1 Chapter 9 reference.


240 9 • Lists

Access for free at [Link]

Common questions

Powered by AI

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' .

You might also like