Python Collections: Strings, Lists, and More
Python Collections: Strings, Lists, and More
Chapter Introduction
elcome to Unit 5. In the world of programming, data is the raw material from which we build solutions. While simple variables can hold
W
a single piece of data, the real power of programming is unlocked when we can work with groups of data. Collections are the
fundamental building blocks in Python for storing, organizing, and managing these groups. This chapter will provide a comprehensive,
exam-oriented exploration of Python's core collection types: Strings, Lists, Tuples, Sets, and Dictionaries. We will deconstruct their
properties, examine their unique strengths, and learn how to manipulate them effectively. Mastering these data structures is not just an
academic exercise; it is an essential skill for solving any significant programming problem, forming the bedrock upon which more
complex programs are built.
--------------------------------------------------------------------------------
collection(also known as a container) is a programmingconstruct—a data type specifically designed to group and store other
A
objects. Think of a collection as a box that can hold multiple items, allowing you to carry them all around using a single name.
he need for collections is intuitive and mirrors how we organize information in daily life. Imagine trying to create a shopping list where
T
each item required a separate piece of paper. It would be incredibly inefficient. Instead, we use a single list—a collection—to hold all the
items. Similarly, a phonebook is a collection that maps names to numbers. Without such structures, programs would be limited to trivial
tasks. The ability to store multiple student grades in one list, or all employee details in a single data structure, is what makes
programming a powerful tool for solving real-world problems.
ifferent collections have different properties, and choosing the right one for the job is a critical programming skill. Some collections
D
maintain a specific order, some are designed to be changed after creation, while others enforce uniqueness among their items.
Understanding these characteristics is key to writing efficient and correct code. We will begin our exploration with the most fundamental
collection of all, one we have already encountered but will now examine in depth: the string.
1. O rdered: The characters in a string have a defined,predictable position. The first character is always at the beginning, the
second follows it, and so on. This reliable ordering allows us to access characters by their position.
2. Immutable: Once a string is created, it cannot bechanged in-place. Any operation that appears to modify a string, such as
replacing a character, actually creates and returns an entirelynewstring. This is a critical concept.
TypeError
Attempting to change a character in a string will result in a , a common point of examination.
Create a string
#
my_string = "Python"
'Python'as follows:
We can visualize the indices for the string
[start:stop:step]
licingis the technique for extracting a portionof a string (a substring). It uses the syntax
S stopis the
,where
first indexnotincluded in the slice.
● [1:4]extracts characters from index 1 up to (butnot including) index 4 (
s 'yth'
).
● s[:3]extracts characters from the beginning up toindex 3 (
'Pyt' ).
● s[2:]extracts characters from index 2 all the wayto the end (
'thon' ).
● s[-2:]extracts the last two characters (
'on' ).
Concatenation (
+) 'Hello' + ' ' + 'World'results in
J oins two strings together to create a new string.
'Hello World'
.
Repetition (
* ) 'Go' *
reates a new string by repeating an existing string a specified number of times.
C
3results in
'GoGoGo'.
Membership (
in
) Trueor
hecks if a substring exists within a larger string, returning
C False 'on' in
.
'Python'results in
True .
.upper()
eturns a new string with all characters
R 'Python'.upper()results in
'PYTHON'
.
converted to uppercase.
.find(sub)
eturns the index of the first occurrence of
R 'Python'.find('ho')results in
3.
sub
-1if not found.
. Returns
replace(old,
. eturns a new string where all
R Hello'.replace('l', 'w')results in
'
new)
oldare replaced with
occurrences of new
.
'Hewwo'
.
.split(sep)
eturns a list of substrings, splitting the
R cat,dog,fish'.split(',')results in
'
sep
original string at the separator . ['cat', 'dog', 'fish']
.
.join(iterable)
J oins elements of an iterable (like a list) -'.join(['a', 'b', 'c'])results in
'
into a single string, using the string as a 'a-b-c'
.
separator.
.isalpha()
Trueif all characters in the string
eturns
R 'abc'.isalpha()results in
True
.
Falseotherwise.
are alphabetic,
ame = "Adam"
n
age = 20
# Using an f-string to embed variables
message = f"{name} is {age} years old."
print(message)
Output:
#
# Adam is 20 years old.
trings are powerful but rigid due to their immutability. For a collection that needs to be modified after creation, we turn to Python's most
S
versatile sequence type: the list.
1. M utable: This is the key difference from strings.Lists can be changed in-place. You can add, remove, or change elements
after the list has been created.
2. Ordered: A list maintains the order of insertion.The first item added stays at the beginning, and subsequent items are added
to the end, unless specified otherwise.
3. Allows Duplicates: A list can contain multiple instancesof the same element.
A list of integers
#
scores = [95, 88, 73, 95, 100]
J ust like strings, lists supportzero-based indexingto access elements andslicingto extract sub-lists.The syntax and behavior are
identical.
.append(item)
itemto the end of the list.
Adds a single tems = [1,
i [1, 2, 3]
2]
<br>
[Link](3)
.extend(list)
listto
ppends all items from another
A tems = [1,
i 1, 2, 3,
[
the end. 2]
<br>
[Link]([3, 4])
4]
insert(i,
. itemat a specific index
Inserts an i. tems = [1,
i [1, 2, 3]
item)
3]
<br>
[Link](1, 2)
.remove(item)
item
emoves thefirstoccurrence of
R tems = [1, 2, 3,
i [1, 3, 2]
from the list. Raises aValueErrorif 2]
<br>
[Link](2)
the item is not found.
.pop(i)
emoves and returns the item at index
R i. i
tems = [1, 2, 1, 3](and
[
iis omitted, it removes and returns the
If 3]
<br>
[Link](1) 2)
returns
last item.
forloop:
Using a
s quares = []
for x in range(10):
[Link](x**2)
Access the element in the first row (index 0), second column (index 1)
#
element = matrix[0][1]
print(element) # Output: 2
hile lists are incredibly flexible due to their mutability, some situations require a guarantee that data will not change. For this, Python
W
provides another sequence type: the tuple.
A tuple of coordinates
#
point = (10, 20)
peculiar but important syntax rule applies when creating a tuple with a single element: it must have a trailing comma. This
A
distinguishes it from a value simply enclosed in parentheses for mathematical grouping.
Accessing elements viaindexing and slicingworksexactly as it does for strings and lists.
● uple Packing: When you assign several comma-separatedvalues to a single variable, Python "packs" them into a tuple.
T
● Tuple Unpacking: You can assign the elements of atuple to multiple variables in a single statement. This is known as
"unpacking" and is extremely useful for assignments.
● ata Integrity: Use a tuple for collections of datathat should not be modified after creation. Examples include configuration
D
settings, fixed coordinates, or records from a database.
● Performance: Tuples can be slightly more memory-efficientand faster to process than lists in certain contexts, as their fixed
size allows for internal optimizations.
● Dictionary Keys: Dictionaries require their keys tobe immutable. Since lists are mutable, they cannot be used as dictionary
keys, but tuples can.
rom ordered collections, we now shift our focus to collections where order is not a primary concern, but uniqueness is paramount,
F
which brings us to the set.
. U
1 nordered: The items in a set do not have a fixedposition or index. The order in which items are stored is not guaranteed.
2. Mutable: Sets can be modified after creation; youcan add or remove elements.
3. Unique Elements: Sets automatically enforce uniqueness.If you attempt to add an item that is already present, the set
remains unchanged.
Union (
|) set_a = {1, 2,
ombines all unique elements from both sets.<br>
C
3}
<br>
set_b = {3, 4, 5}<br>
set_a | set_bresults in
{1, 2, 3, 4, 5}
.
Intersection (
&) set_a = {1, 2,
inds only the elements that are present in both sets.<br>
F
3}
<br>
set_b = {3, 4, 5} <br>
set_a & set_bresults in{3}
.
Difference (
-) set_a =
inds elements that are in the first set but not in the second set.<br>
F
{1, 2, 3}
<br>
set_b = {3, 4, 5} <br>
set_a - set_bresultsin{1, 2}
.
ymmetric Difference F
S set_a = {1, 2,
inds elements that are in one set or the other, but not both.<br>
(
^) 3}
<br>
set_b = {3, 4, 5} <br>
set_a ^ set_bresults in
{1, 2, 4, 5} .
Having explored collections that store individual items, we now turn to a data structure designed to store data in pairs: the dictionary.
1. Mutable: You can add, remove, and change key-valuepairs after the dictionary is created.
2. O rdered (Modern Python): As of Python 3.7+, dictionaries preserve the order in which items were inserted. In older versions,
they were unordered. For exams, it is safe to mention this modern behavior.
3. Unique, Immutable Keys: The keys within a dictionarymust be unique. They must also be of an immutable type (e.g., string,
number, or tuple). Values, however, can be of any type and can be duplicated.
.keys()
view object displaying a list of all the keys
A ist([Link]())results in
l ['name',
in the dictionary. 'major', 'year']
.values()
view object displaying a list of all the
A ist([Link]())results in
l
values in the dictionary. ['Alice', 'Computer Science', 3]
.items()
view object displaying a list of key-value
A ist([Link]())results in
l [('name',
tuple pairs. 'Alice'), ('major', 'Computer
Science'), ('year', 3)]
get(key,
. key
eturns the value for
R keyis not
. If [Link]('gpa', 'N/A')returns
s 'N/A'
default)
default(or
found, it returns Noneif because 'gpa' key does not exist.
defaultis omitted) instead of raising a
KeyError
.
ith a firm grasp of each individual collection type, it is now time to consolidate our knowledge and perform a direct comparison to
W
guide our selection process.
7.0 Comparative Analysis of Python Collections
hoosing the correct data structure is one of the most important decisions a programmer makes. The choice can significantly impact a
C
program's performance, readability, and correctness. This section provides a consolidated, at-a-glance reference to help you decide
which collection to use for a given problem—a critical skill frequently tested in programming exams.
Indexing Integer index Integer index Integer index Not applicable Key-based
llows
A Yes Yes Yes No No (for keys)
Duplicates?
rimary
P toring and
S
A Protecting data nsuring
E ast lookups
F
Use-Case manipulating textual general-purpose integrity; use as uniqueness and based on
data. , flexible ict keys.
d math operations. key-value
sequence. mapping.
In summary, the key decision points for selecting a data structure can be framed as a series of questions. If you need to store an
ordered sequence of items that can be changed, use aList. If that data should be fixed and never change,use aTuple. If you only
need to know whether an item exists in a collection and do not care about order or duplicates, use aSet. Finally, if you need to store
and retrieve data based on a unique identifier or label, use aDictionary.
With this theoretical framework established, we now turn to applying these collections to solve practical problems.
Use the split() method to get a list of words. The length of this list is the word count.
#
words = [Link]()
word_count = len(words)
def display_menu():
"""Prints the main menu of options for the user."""
print("\n--- Simple Phonebook Menu ---")
print("1. Look up a contact")
print("2. Add a new contact")
print("3. Delete a contact")
print("4. Exit")
print("-----------------------------\n")
2. Implement a simple loop that runs until the user chooses to exit.
#
while True:
display_menu()
choice = input("Enter your choice (1-4): ")
else:
# Handle invalid menu choices
print("Invalid choice. Please enter a number between 1 and 4.")
c) Students who are only in the Coding Club but not the Robotics Club (difference)
#
only_coding = coding_set.difference(robotics_set)
print(f"Students only in the Coding Club: {only_coding}")
d) Students who are in either club, but not both (symmetric difference)
#
either_not_both = coding_set.symmetric_difference(robotics_set)
print(f"Students in one club but not both: {either_not_both}")