5.1 Understanding Sequences in Python

Sequences are one of the most fundamental and powerful concepts in Python. A sequence is an ordered collection of items where each item has a specific position (index). Python provides several built-in sequence types: lists, tuples, strings, and ranges.

In this tutorial, you’ll learn how to work with sequences effectively, understand their differences, and master common operations.

5.2 What are Sequences?

Sequences share common characteristics: - Ordered: Items have a specific position - Indexable: You can access items by their position - Iterable: You can loop through them - Support common operations: len(), in, slicing, etc.

# Examples of different sequence types
my_list = [1, 2, 3, 4, 5]           # List - mutable
my_tuple = (1, 2, 3, 4, 5)          # Tuple - immutable
my_string = "Hello"                 # String - immutable
my_range = range(1, 6)              # Range - immutable

print(f"List: {my_list}")
print(f"Tuple: {my_tuple}")
print(f"String: {my_string}")
print(f"Range: {list(my_range)}")  # Convert to list to see values
List: [1, 2, 3, 4, 5]
Tuple: (1, 2, 3, 4, 5)
String: Hello
Range: [1, 2, 3, 4, 5]

5.3 The len() Function

The len() function returns the number of items in a sequence.

fruits = ["apple", "banana", "cherry", "date"]
numbers = (10, 20, 30, 40, 50)
message = "Python is awesome!"

print(f"Number of fruits: {len(fruits)}")
print(f"Number of numbers: {len(numbers)}")
print(f"Length of message: {len(message)}")
print(f"Range length: {len(range(0, 100))}")
Number of fruits: 4
Number of numbers: 5
Length of message: 18
Range length: 100

5.4 The in Operation

The in operator checks if an item exists in a sequence. It returns True or False.

colors = ["red", "green", "blue", "yellow"]
vowels = "aeiou"

# Check if item is in list
print(f"Is 'red' in colors? {'red' in colors}")
print(f"Is 'purple' in colors? {'purple' in colors}")

# Check if character is in string
print(f"Is 'a' in vowels? {'a' in vowels}")
print(f"Is 'x' in vowels? {'x' in vowels}")

# Using 'not in'
print(f"Is 'purple' not in colors? {'purple' not in colors}")
Is 'red' in colors? True
Is 'purple' in colors? False
Is 'a' in vowels? True
Is 'x' in vowels? False
Is 'purple' not in colors? True

Practical example:

# Check if user is admin
admin_users = ["alice", "bob", "charlie"]
current_user = "bob"

if current_user in admin_users:
    print(f"{current_user} has admin access")
else:
    print(f"{current_user} does not have admin access")
bob has admin access

5.5 Indexing

Indexing allows you to access individual items in a sequence using their position.

Important: Python uses zero-based indexing (first item is at index 0).

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Positive indexing (from the beginning)
print(f"First fruit: {fruits[0]}")
print(f"Second fruit: {fruits[1]}")
print(f"Third fruit: {fruits[2]}")

# Negative indexing (from the end)
print(f"Last fruit: {fruits[-1]}")
print(f"Second to last: {fruits[-2]}")
print(f"Third to last: {fruits[-3]}")
First fruit: apple
Second fruit: banana
Third fruit: cherry
Last fruit: elderberry
Second to last: date
Third to last: cherry

Indexing visualization:

# Index:    0    1    2    3    4
# Index:   -5   -4   -3   -2   -1
letters = ['a', 'b', 'c', 'd', 'e']

print("Positive indexing:")
print(f"letters[0] = {letters[0]}")
print(f"letters[2] = {letters[2]}")

print("\nNegative indexing:")
print(f"letters[-1] = {letters[-1]}")
print(f"letters[-3] = {letters[-3]}")
Positive indexing:
letters[0] = a
letters[2] = c

Negative indexing:
letters[-1] = e
letters[-3] = c

Indexing strings:

message = "Python"

print(f"First character: {message[0]}")
print(f"Last character: {message[-1]}")
print(f"Third character: {message[2]}")
First character: P
Last character: n
Third character: t

5.6 Slicing

Slicing extracts a portion of a sequence using the syntax: sequence[start:stop:step]

  • start: Beginning index (inclusive)
  • stop: Ending index (exclusive)
  • step: Increment (default is 1)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Basic slicing
print(f"numbers[2:5] = {numbers[2:5]}")     # Items at index 2, 3, 4
print(f"numbers[0:3] = {numbers[0:3]}")     # First three items
print(f"numbers[5:] = {numbers[5:]}")       # From index 5 to end
print(f"numbers[:4] = {numbers[:4]}")       # From beginning to index 3
print(f"numbers[:] = {numbers[:]}")         # Copy entire list
numbers[2:5] = [2, 3, 4]
numbers[0:3] = [0, 1, 2]
numbers[5:] = [5, 6, 7, 8, 9]
numbers[:4] = [0, 1, 2, 3]
numbers[:] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Slicing with step:

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

print(f"Every second item: {numbers[::2]}")          # Step of 2
print(f"Every third item: {numbers[::3]}")           # Step of 3
print(f"Reversed list: {numbers[::-1]}")             # Negative step reverses
print(f"Every second item from 1 to 8: {numbers[1:8:2]}")
Every second item: [0, 2, 4, 6, 8]
Every third item: [0, 3, 6, 9]
Reversed list: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Every second item from 1 to 8: [1, 3, 5, 7]

Slicing strings:

text = "Python Programming"

print(f"First 6 characters: {text[:6]}")
print(f"Last 11 characters: {text[-11:]}")
print(f"Every other character: {text[::2]}")
print(f"Reversed string: {text[::-1]}")
First 6 characters: Python
Last 11 characters: Programming
Every other character: Pto rgamn
Reversed string: gnimmargorP nohtyP

Negative indices in slicing:

fruits = ["apple", "banana", "cherry", "date", "elderberry"]

print(f"Last three fruits: {fruits[-3:]}")
print(f"All except last two: {fruits[:-2]}")
print(f"Middle items: {fruits[1:-1]}")
Last three fruits: ['cherry', 'date', 'elderberry']
All except last two: ['apple', 'banana', 'cherry']
Middle items: ['banana', 'cherry', 'date']

5.7 Lists - Mutable Sequences

Lists are mutable (changeable) sequences that can store any type of data.

Creating Lists

# Different ways to create lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
nested = [[1, 2], [3, 4], [5, 6]]

print(f"Empty list: {empty_list}")
print(f"Numbers: {numbers}")
print(f"Mixed types: {mixed}")
print(f"Nested list: {nested}")

# Using list() constructor
from_string = list("Python")
from_range = list(range(5))

print(f"From string: {from_string}")
print(f"From range: {from_range}")
Empty list: []
Numbers: [1, 2, 3, 4, 5]
Mixed types: [1, 'hello', 3.14, True]
Nested list: [[1, 2], [3, 4], [5, 6]]
From string: ['P', 'y', 't', 'h', 'o', 'n']
From range: [0, 1, 2, 3, 4]

Adding Items to Lists

# append() - adds one item to the end
fruits = ["apple", "banana"]
fruits.append("cherry")
print(f"After append: {fruits}")

# extend() - adds multiple items
fruits.extend(["date", "elderberry"])
print(f"After extend: {fruits}")

# insert() - adds item at specific position
fruits.insert(1, "apricot")  # Insert at index 1
print(f"After insert: {fruits}")

# Using + operator
more_fruits = fruits + ["fig", "grape"]
print(f"Using + operator: {more_fruits}")
After append: ['apple', 'banana', 'cherry']
After extend: ['apple', 'banana', 'cherry', 'date', 'elderberry']
After insert: ['apple', 'apricot', 'banana', 'cherry', 'date', 'elderberry']
Using + operator: ['apple', 'apricot', 'banana', 'cherry', 'date', 'elderberry', 'fig', 'grape']

Removing Items from Lists

numbers = [1, 2, 3, 4, 5, 3, 6, 7]

# remove() - removes first occurrence of value
numbers_copy = numbers.copy()
numbers_copy.remove(3)
print(f"After remove(3): {numbers_copy}")

# pop() - removes and returns item at index (default: last item)
numbers_copy = numbers.copy()
last_item = numbers_copy.pop()
print(f"Popped item: {last_item}")
print(f"After pop(): {numbers_copy}")

second_item = numbers_copy.pop(1)
print(f"Popped item at index 1: {second_item}")
print(f"After pop(1): {numbers_copy}")

# del - deletes item(s) by index or slice
numbers_copy = numbers.copy()
del numbers_copy[0]
print(f"After del [0]: {numbers_copy}")

numbers_copy = numbers.copy()
del numbers_copy[1:4]
print(f"After del [1:4]: {numbers_copy}")

# clear() - removes all items
numbers_copy = numbers.copy()
numbers_copy.clear()
print(f"After clear(): {numbers_copy}")
After remove(3): [1, 2, 4, 5, 3, 6, 7]
Popped item: 7
After pop(): [1, 2, 3, 4, 5, 3, 6]
Popped item at index 1: 2
After pop(1): [1, 3, 4, 5, 3, 6]
After del [0]: [2, 3, 4, 5, 3, 6, 7]
After del [1:4]: [1, 5, 3, 6, 7]
After clear(): []

Modifying Lists

# Lists are mutable - you can change items
colors = ["red", "green", "blue"]
colors[1] = "yellow"  # Change second item
print(f"Modified list: {colors}")

# Change multiple items with slicing
numbers = [0, 1, 2, 3, 4, 5]
numbers[1:4] = [10, 20, 30]
print(f"After slice assignment: {numbers}")
Modified list: ['red', 'yellow', 'blue']
After slice assignment: [0, 10, 20, 30, 4, 5]

Sorting Lists

# sort() - sorts the list in place
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()
print(f"Sorted (ascending): {numbers}")

numbers.sort(reverse=True)
print(f"Sorted (descending): {numbers}")

# sorted() - returns a new sorted list
original = [3, 1, 4, 1, 5, 9, 2, 6]
sorted_list = sorted(original)
print(f"Original: {original}")
print(f"Sorted copy: {sorted_list}")

# Sorting strings
words = ["banana", "apple", "cherry", "date"]
words.sort()
print(f"Sorted words: {words}")

# Case-insensitive sorting
mixed_case = ["banana", "Apple", "cherry", "Date"]
mixed_case.sort(key=str.lower)
print(f"Case-insensitive sort: {mixed_case}")
Sorted (ascending): [1, 1, 2, 3, 4, 5, 6, 9]
Sorted (descending): [9, 6, 5, 4, 3, 2, 1, 1]
Original: [3, 1, 4, 1, 5, 9, 2, 6]
Sorted copy: [1, 1, 2, 3, 4, 5, 6, 9]
Sorted words: ['apple', 'banana', 'cherry', 'date']
Case-insensitive sort: ['Apple', 'banana', 'cherry', 'Date']

Other useful list methods:

numbers = [1, 2, 3, 2, 4, 2, 5]

# count() - counts occurrences
print(f"Count of 2: {numbers.count(2)}")

# index() - finds first occurrence
print(f"Index of 3: {numbers.index(3)}")

# reverse() - reverses the list in place
numbers.reverse()
print(f"Reversed: {numbers}")
Count of 2: 3
Index of 3: 2
Reversed: [5, 2, 4, 2, 3, 2, 1]

5.8 Tuples - Immutable Sequences

Tuples are immutable (unchangeable) sequences. Once created, you cannot modify, add, or remove items.

Creating Tuples

# Different ways to create tuples
empty_tuple = ()
single_item = (1,)  # Note the comma!
numbers = (1, 2, 3, 4, 5)
mixed = (1, "hello", 3.14, True)
without_parentheses = 1, 2, 3  # Parentheses are optional

print(f"Empty tuple: {empty_tuple}")
print(f"Single item: {single_item}")
print(f"Numbers: {numbers}")
print(f"Mixed: {mixed}")
print(f"Without parentheses: {without_parentheses}")

# Using tuple() constructor
from_list = tuple([1, 2, 3])
from_string = tuple("Python")

print(f"From list: {from_list}")
print(f"From string: {from_string}")
Empty tuple: ()
Single item: (1,)
Numbers: (1, 2, 3, 4, 5)
Mixed: (1, 'hello', 3.14, True)
Without parentheses: (1, 2, 3)
From list: (1, 2, 3)
From string: ('P', 'y', 't', 'h', 'o', 'n')

Why Use Tuples?

## Tuples are faster than lists
## Tuples protect data from accidental changes
## Tuples can be used as dictionary keys (lists cannot)
## Tuples are used for multiple return values from functions

coordinates = (10, 20)  # Coordinates shouldn't change
rgb_color = (255, 0, 128)  # Color values are fixed

print(f"Coordinates: {coordinates}")
print(f"RGB Color: {rgb_color}")

# Trying to modify a tuple causes an error
# coordinates[0] = 15  # This would raise: TypeError
Coordinates: (10, 20)
RGB Color: (255, 0, 128)

Tuple Operations

# Tuples support indexing, slicing, and other sequence operations
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

print(f"First item: {numbers[0]}")
print(f"Last item: {numbers[-1]}")
print(f"Slice [2:5]: {numbers[2:5]}")
print(f"Every second item: {numbers[::2]}")

# count() and index() methods
values = (1, 2, 3, 2, 4, 2, 5)
print(f"Count of 2: {values.count(2)}")
print(f"Index of 3: {values.index(3)}")

# Concatenation and repetition
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
repeated = tuple1 * 3

print(f"Combined: {combined}")
print(f"Repeated: {repeated}")
First item: 0
Last item: 9
Slice [2:5]: (2, 3, 4)
Every second item: (0, 2, 4, 6, 8)
Count of 2: 3
Index of 3: 2
Combined: (1, 2, 3, 4, 5, 6)
Repeated: (1, 2, 3, 1, 2, 3, 1, 2, 3)

5.9 Lists vs Tuples: Key Differences

# Create a list and a tuple with same values
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)

print("Similarities:")
print(f"Both support indexing: list[0]={my_list[0]}, tuple[0]={my_tuple[0]}")
print(f"Both support slicing: list[1:3]={my_list[1:3]}, tuple[1:3]={my_tuple[1:3]}")
print(f"Both support len(): list={len(my_list)}, tuple={len(my_tuple)}")
print(f"Both support 'in': 3 in list={3 in my_list}, 3 in tuple={3 in my_tuple}")

print("\nDifferences:")
print(f"List is mutable: {my_list}")
my_list[0] = 100
print(f"After modification: {my_list}")

print(f"\nTuple is immutable: {my_tuple}")
# my_tuple[0] = 100  # This would raise TypeError
print("Cannot modify tuple items!")
Similarities:
Both support indexing: list[0]=1, tuple[0]=1
Both support slicing: list[1:3]=[2, 3], tuple[1:3]=(2, 3)
Both support len(): list=5, tuple=5
Both support 'in': 3 in list=True, 3 in tuple=True

Differences:
List is mutable: [1, 2, 3, 4, 5]
After modification: [100, 2, 3, 4, 5]

Tuple is immutable: (1, 2, 3, 4, 5)
Cannot modify tuple items!

Summary Table:

Feature List Tuple
Syntax [1, 2, 3] (1, 2, 3)
Mutable Yes ✓ No ✗
Speed Slower Faster
Methods Many (append, remove, etc.) Few (count, index)
Use case Data that changes Fixed data
Dictionary key No ✗ Yes ✓

5.10 Math Operations on Sequences

numbers = [1, 2, 3, 4, 5]
tuple_nums = (10, 20, 30, 40, 50)

# Sum of all items
print(f"Sum of list: {sum(numbers)}")
print(f"Sum of tuple: {sum(tuple_nums)}")

# Minimum and maximum
print(f"Min: {min(numbers)}, Max: {max(numbers)}")

# Length
print(f"Length: {len(numbers)}")

# Concatenation
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined = list1 + list2
print(f"Concatenated: {combined}")

# Repetition
repeated = [1, 2] * 3
print(f"Repeated: {repeated}")

# Membership
print(f"Is 3 in numbers? {3 in numbers}")
Sum of list: 15
Sum of tuple: 150
Min: 1, Max: 5
Length: 5
Concatenated: [1, 2, 3, 4, 5, 6]
Repeated: [1, 2, 1, 2, 1, 2]
Is 3 in numbers? True

Working with numeric sequences:

scores = [85, 92, 78, 90, 88]

total = sum(scores)
count = len(scores)
average = total / count
highest = max(scores)
lowest = min(scores)

print(f"Total: {total}")
print(f"Count: {count}")
print(f"Average: {average:.2f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
Total: 433
Count: 5
Average: 86.60
Highest: 92
Lowest: 78

5.11 Unpacking Sequences

Unpacking allows you to assign sequence items to multiple variables in one line.

Basic Unpacking

# Unpacking a list
coordinates = [10, 20]
x, y = coordinates
print(f"x = {x}, y = {y}")

# Unpacking a tuple
person = ("Alice", 25, "New York")
name, age, city = person
print(f"Name: {name}, Age: {age}, City: {city}")

# Unpacking a string
code = "RGB"
r, g, b = code
print(f"r={r}, g={g}, b={b}")
x = 10, y = 20
Name: Alice, Age: 25, City: New York
r=R, g=G, b=B

Extended Unpacking with *

# Using * to capture multiple values
numbers = [1, 2, 3, 4, 5, 6]

# Get first, last, and everything in between
first, *middle, last = numbers
print(f"First: {first}")
print(f"Middle: {middle}")
print(f"Last: {last}")

# Get first two and the rest
first, second, *rest = numbers
print(f"First: {first}, Second: {second}, Rest: {rest}")

# Get all but the last
*most, last = numbers
print(f"Most: {most}, Last: {last}")
First: 1
Middle: [2, 3, 4, 5]
Last: 6
First: 1, Second: 2, Rest: [3, 4, 5, 6]
Most: [1, 2, 3, 4, 5], Last: 6

Swapping Values

# Easy value swapping with unpacking
a = 5
b = 10
print(f"Before swap: a={a}, b={b}")

a, b = b, a
print(f"After swap: a={a}, b={b}")

# Rotating values
x, y, z = 1, 2, 3
print(f"Before rotation: x={x}, y={y}, z={z}")

x, y, z = z, x, y
print(f"After rotation: x={x}, y={y}, z={z}")
Before swap: a=5, b=10
After swap: a=10, b=5
Before rotation: x=1, y=2, z=3
After rotation: x=3, y=1, z=2

Unpacking in Loops

# Unpacking tuples in a loop
people = [
    ("Alice", 25),
    ("Bob", 30),
    ("Charlie", 35)
]

for name, age in people:
    print(f"{name} is {age} years old")

# Unpacking with enumerate
fruits = ["apple", "banana", "cherry"]

for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
Alice is 25 years old
Bob is 30 years old
Charlie is 35 years old
0: apple
1: banana
2: cherry

5.12 Strings as Sequences

Strings are immutable sequences of characters.

String Operations

message = "Python Programming"

# Indexing
print(f"First character: {message[0]}")
print(f"Last character: {message[-1]}")

# Slicing
print(f"First word: {message[:6]}")
print(f"Second word: {message[7:]}")
print(f"Every other character: {message[::2]}")

# Length
print(f"Length: {len(message)}")

# Membership
print(f"'Python' in message: {'Python' in message}")
print(f"'Java' in message: {'Java' in message}")

# Iteration
print("Characters:", end=" ")
for char in message[:6]:
    print(char, end=" ")
print()
First character: P
Last character: g
First word: Python
Second word: Programming
Every other character: Pto rgamn
Length: 18
'Python' in message: True
'Java' in message: False
Characters: P y t h o n 

String Methods

text = "  Hello, World!  "

# Case conversion
print(f"Upper: {text.upper()}")
print(f"Lower: {text.lower()}")
print(f"Title: {text.title()}")

# Removing whitespace
print(f"Strip: '{text.strip()}'")
print(f"Left strip: '{text.lstrip()}'")
print(f"Right strip: '{text.rstrip()}'")

# Splitting and joining
words = "apple,banana,cherry".split(",")
print(f"Split: {words}")

joined = " - ".join(words)
print(f"Joined: {joined}")

# Replacing
replaced = "Hello World".replace("World", "Python")
print(f"Replaced: {replaced}")

# Finding
position = "Hello World".find("World")
print(f"Position of 'World': {position}")
Upper:   HELLO, WORLD!  
Lower:   hello, world!  
Title:   Hello, World!  
Strip: 'Hello, World!'
Left strip: 'Hello, World!  '
Right strip: '  Hello, World!'
Split: ['apple', 'banana', 'cherry']
Joined: apple - banana - cherry
Replaced: Hello Python
Position of 'World': 6

String Formatting

name = "Alice"
age = 25
height = 5.7

# f-strings (recommended)
print(f"My name is {name}, I'm {age} years old and {height} feet tall")

# format() method
print("My name is {}, I'm {} years old".format(name, age))

# % operator (old style)
print("My name is %s, I'm %d years old" % (name, age))

# Formatting numbers
pi = 3.14159265
print(f"Pi rounded to 2 decimals: {pi:.2f}")
print(f"Pi rounded to 4 decimals: {pi:.4f}")
My name is Alice, I'm 25 years old and 5.7 feet tall
My name is Alice, I'm 25 years old
My name is Alice, I'm 25 years old
Pi rounded to 2 decimals: 3.14
Pi rounded to 4 decimals: 3.1416

5.13 Ranges

Ranges represent immutable sequences of numbers, commonly used in loops.

Creating Ranges

# range(stop) - from 0 to stop-1
r1 = range(5)
print(f"range(5): {list(r1)}")

# range(start, stop) - from start to stop-1
r2 = range(2, 8)
print(f"range(2, 8): {list(r2)}")

# range(start, stop, step) - with custom step
r3 = range(0, 10, 2)
print(f"range(0, 10, 2): {list(r3)}")

# Negative step (counting backwards)
r4 = range(10, 0, -1)
print(f"range(10, 0, -1): {list(r4)}")

# Even numbers
evens = range(0, 20, 2)
print(f"Even numbers: {list(evens)}")

# Odd numbers
odds = range(1, 20, 2)
print(f"Odd numbers: {list(odds)}")
range(5): [0, 1, 2, 3, 4]
range(2, 8): [2, 3, 4, 5, 6, 7]
range(0, 10, 2): [0, 2, 4, 6, 8]
range(10, 0, -1): [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
Even numbers: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
Odd numbers: [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Using Ranges in Loops

# Basic loop
print("Counting to 5:")
for i in range(1, 6):
    print(i, end=" ")
print()

# Loop with index
fruits = ["apple", "banana", "cherry"]
print("\nFruits with index:")
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")

# Countdown
print("\nCountdown:")
for i in range(5, 0, -1):
    print(i, end=" ")
print("Blast off!")
Counting to 5:
1 2 3 4 5 

Fruits with index:
0: apple
1: banana
2: cherry

Countdown:
5 4 3 2 1 Blast off!

Range Operations

# Ranges support sequence operations
r = range(0, 10, 2)

print(f"Length: {len(r)}")
print(f"First item: {r[0]}")
print(f"Last item: {r[-1]}")
print(f"Is 4 in range? {4 in r}")
print(f"Is 5 in range? {5 in r}")
print(f"Min: {min(r)}, Max: {max(r)}")

# Slicing ranges
print(f"Slice [1:4]: {list(r[1:4])}")
Length: 5
First item: 0
Last item: 8
Is 4 in range? True
Is 5 in range? False
Min: 0, Max: 8
Slice [1:4]: [2, 4, 6]

5.14 Practical Examples

Example 1: Managing a Shopping List

# Create shopping list
shopping_list = []

# Add items
shopping_list.append("milk")
shopping_list.append("bread")
shopping_list.extend(["eggs", "butter", "cheese"])

print(f"Shopping list: {shopping_list}")
print(f"Number of items: {len(shopping_list)}")

# Check if item is in list
if "milk" in shopping_list:
    print("Don't forget to buy milk!")

# Remove an item
shopping_list.remove("bread")
print(f"After removing bread: {shopping_list}")

# Sort alphabetically
shopping_list.sort()
print(f"Sorted list: {shopping_list}")
Shopping list: ['milk', 'bread', 'eggs', 'butter', 'cheese']
Number of items: 5
Don't forget to buy milk!
After removing bread: ['milk', 'eggs', 'butter', 'cheese']
Sorted list: ['butter', 'cheese', 'eggs', 'milk']

Example 2: Processing Student Grades

# Student grades (name, score)
students = [
    ("Alice", 95),
    ("Bob", 87),
    ("Charlie", 92),
    ("Diana", 88),
    ("Eve", 91)
]

# Calculate statistics
scores = [score for name, score in students]
average = sum(scores) / len(scores)

print(f"Average score: {average:.2f}")
print(f"Highest score: {max(scores)}")
print(f"Lowest score: {min(scores)}")

# Find top student
top_student = max(students, key=lambda x: x[1])
print(f"\nTop student: {top_student[0]} with score {top_student[1]}")

# Students above average
print("\nStudents above average:")
for name, score in students:
    if score > average:
        print(f"  {name}: {score}")
Average score: 90.60
Highest score: 95
Lowest score: 87

Top student: Alice with score 95

Students above average:
  Alice: 95
  Charlie: 92
  Eve: 91

Example 3: Text Analysis

text = "Python is amazing and Python is powerful"

# Convert to lowercase and split into words
words = text.lower().split()

# Count total words
print(f"Total words: {len(words)}")

# Count unique words
unique_words = list(set(words))
print(f"Unique words: {len(unique_words)}")

# Count occurrences of a specific word
python_count = words.count("python")
print(f"'python' appears {python_count} times")

# Find word positions
for i, word in enumerate(words):
    if word == "python":
        print(f"'python' found at position {i}")
Total words: 7
Unique words: 5
'python' appears 2 times
'python' found at position 0
'python' found at position 4

5.15 Practice Exercises

Exercise 1: List Manipulation

Create a list of numbers and perform various operations:

# Create a list of numbers from 1 to 10
numbers =

# Add 11 and 12 to the end

# Remove the number 5

# Insert 100 at index 3

# Print the final list

Exercise 2: Tuple Unpacking

Create a function that returns multiple values:

def get_stats(numbers):
    # Return min, max, and average as a tuple
    pass

# Test with a list
data = [10, 20, 30, 40, 50]
# Unpack the results
minimum, maximum, average = get_stats(data)
# Print results

Exercise 3: String Slicing

Extract parts of an email address:

email = "user.name@example.com"

# Extract username (before @)
username =

# Extract domain (after @)
domain =

# Print both

Exercise 4: Working with Ranges

Print all multiples of 3 between 1 and 30:

# Use range to generate multiples of 3

5.16 Solutions

Solution 1:

Click to show solution
numbers = list(range(1, 11))
print(f"Initial: {numbers}")

numbers.append(11)
numbers.append(12)
print(f"After adding 11, 12: {numbers}")

numbers.remove(5)
print(f"After removing 5: {numbers}")

numbers.insert(3, 100)
print(f"After inserting 100 at index 3: {numbers}")
Initial: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
After adding 11, 12: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
After removing 5: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11, 12]
After inserting 100 at index 3: [1, 2, 3, 100, 4, 6, 7, 8, 9, 10, 11, 12]

Solution 2:

Click to show solution
def get_stats(numbers):
    return min(numbers), max(numbers), sum(numbers) / len(numbers)

data = [10, 20, 30, 40, 50]
minimum, maximum, average = get_stats(data)

print(f"Minimum: {minimum}")
print(f"Maximum: {maximum}")
print(f"Average: {average}")
Minimum: 10
Maximum: 50
Average: 30.0

Solution 3:

Click to show solution
email = "user.name@example.com"

at_position = email.index('@')
username = email[:at_position]
domain = email[at_position + 1:]

print(f"Username: {username}")
print(f"Domain: {domain}")

# Alternative using split
username, domain = email.split('@')
print(f"\nUsing split - Username: {username}, Domain: {domain}")
Username: user.name
Domain: example.com

Using split - Username: user.name, Domain: example.com

Solution 4:

Click to show solution
print("Multiples of 3 between 1 and 30:")
for num in range(3, 31, 3):
    print(num, end=" ")
print()

# Alternative
multiples = list(range(3, 31, 3))
print(f"\nAs a list: {multiples}")
Multiples of 3 between 1 and 30:
3 6 9 12 15 18 21 24 27 30 

As a list: [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

5.17 Summary: When to Use Each Sequence Type

Lists

  • Use when: You need to modify the collection (add, remove, change items)
  • Examples: Shopping lists, todo items, user data, scores
  • Key feature: Mutable - can be changed after creation

Tuples

  • Use when: Data should not change, need faster performance
  • Examples: Coordinates, RGB colors, database records, configuration
  • Key feature: Immutable - cannot be changed after creation

Strings

  • Use when: Working with text data
  • Examples: Names, messages, file contents, user input
  • Key feature: Immutable sequence of characters

Ranges

  • Use when: Need sequence of numbers, especially in loops
  • Examples: Loop iterations, number sequences, indexing
  • Key feature: Memory-efficient, immutable

5.18 Key Takeaways

Common Sequence Operations: - len(sequence) - Get length - item in sequence - Check membership - sequence[index] - Access by index - sequence[start:stop:step] - Slicing - min(sequence), max(sequence), sum(sequence) - Math operations

List-Specific Operations: - append(), extend(), insert() - Add items - remove(), pop(), clear() - Remove items - sort(), reverse() - Modify order - Lists are mutable

Tuple Features: - Created with parentheses: (1, 2, 3) - Faster than lists - Can be dictionary keys - Tuples are immutable

Unpacking: - a, b, c = [1, 2, 3] - Basic unpacking - first, *rest = [1, 2, 3, 4] - Extended unpacking - Great for swapping values

Best Practices: - Use lists when data changes - Use tuples for fixed data - Use meaningful variable names - Remember: indexing starts at 0 - Negative indices count from the end

5.19 Next Steps

Now that you understand sequences, you’re ready to learn: - List comprehensions (advanced list creation) - Dictionaries and sets (other data structures) - Loops (for and while) - Functions (processing sequences) - File I/O (reading and writing data)

Keep practicing with sequences - they’re fundamental to Python programming!