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 typesmy_list = [1, 2, 3, 4, 5] # List - mutablemy_tuple = (1, 2, 3, 4, 5) # Tuple - immutablemy_string ="Hello"# String - immutablemy_range =range(1, 6) # Range - immutableprint(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
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 listprint(f"Is 'red' in colors? {'red'in colors}")print(f"Is 'purple' in colors? {'purple'in colors}")# Check if character is in stringprint(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'notin 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 adminadmin_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
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 slicingprint(f"numbers[2:5] = {numbers[2:5]}") # Items at index 2, 3, 4print(f"numbers[0:3] = {numbers[0:3]}") # First three itemsprint(f"numbers[5:] = {numbers[5:]}") # From index 5 to endprint(f"numbers[:4] = {numbers[:4]}") # From beginning to index 3print(f"numbers[:] = {numbers[:]}") # Copy entire list
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print(f"Every second item: {numbers[::2]}") # Step of 2print(f"Every third item: {numbers[::3]}") # Step of 3print(f"Reversed list: {numbers[::-1]}") # Negative step reversesprint(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.
numbers = [1, 2, 3, 2, 4, 2, 5]# count() - counts occurrencesprint(f"Count of 2: {numbers.count(2)}")# index() - finds first occurrenceprint(f"Index of 3: {numbers.index(3)}")# reverse() - reverses the list in placenumbers.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 tuplesempty_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 optionalprint(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() constructorfrom_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 functionscoordinates = (10, 20) # Coordinates shouldn't changergb_color = (255, 0, 128) # Color values are fixedprint(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 operationsnumbers = (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() methodsvalues = (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 repetitiontuple1 = (1, 2, 3)tuple2 = (4, 5, 6)combined = tuple1 + tuple2repeated = tuple1 *3print(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 valuesmy_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={3in my_list}, 3 in tuple={3in my_tuple}")print("\nDifferences:")print(f"List is mutable: {my_list}")my_list[0] =100print(f"After modification: {my_list}")print(f"\nTuple is immutable: {my_tuple}")# my_tuple[0] = 100 # This would raise TypeErrorprint("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 itemsprint(f"Sum of list: {sum(numbers)}")print(f"Sum of tuple: {sum(tuple_nums)}")# Minimum and maximumprint(f"Min: {min(numbers)}, Max: {max(numbers)}")# Lengthprint(f"Length: {len(numbers)}")# Concatenationlist1 = [1, 2, 3]list2 = [4, 5, 6]combined = list1 + list2print(f"Concatenated: {combined}")# Repetitionrepeated = [1, 2] *3print(f"Repeated: {repeated}")# Membershipprint(f"Is 3 in numbers? {3in 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
Unpacking allows you to assign sequence items to multiple variables in one line.
Basic Unpacking
# Unpacking a listcoordinates = [10, 20]x, y = coordinatesprint(f"x = {x}, y = {y}")# Unpacking a tupleperson = ("Alice", 25, "New York")name, age, city = personprint(f"Name: {name}, Age: {age}, City: {city}")# Unpacking a stringcode ="RGB"r, g, b = codeprint(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 valuesnumbers = [1, 2, 3, 4, 5, 6]# Get first, last, and everything in betweenfirst, *middle, last = numbersprint(f"First: {first}")print(f"Middle: {middle}")print(f"Last: {last}")# Get first two and the restfirst, second, *rest = numbersprint(f"First: {first}, Second: {second}, Rest: {rest}")# Get all but the last*most, last = numbersprint(f"Most: {most}, Last: {last}")
# Easy value swapping with unpackinga =5b =10print(f"Before swap: a={a}, b={b}")a, b = b, aprint(f"After swap: a={a}, b={b}")# Rotating valuesx, y, z =1, 2, 3print(f"Before rotation: x={x}, y={y}, z={z}")x, y, z = z, x, yprint(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 looppeople = [ ("Alice", 25), ("Bob", 30), ("Charlie", 35)]for name, age in people:print(f"{name} is {age} years old")# Unpacking with enumeratefruits = ["apple", "banana", "cherry"]for index, fruit inenumerate(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"# Indexingprint(f"First character: {message[0]}")print(f"Last character: {message[-1]}")# Slicingprint(f"First word: {message[:6]}")print(f"Second word: {message[7:]}")print(f"Every other character: {message[::2]}")# Lengthprint(f"Length: {len(message)}")# Membershipprint(f"'Python' in message: {'Python'in message}")print(f"'Java' in message: {'Java'in message}")# Iterationprint("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 conversionprint(f"Upper: {text.upper()}")print(f"Lower: {text.lower()}")print(f"Title: {text.title()}")# Removing whitespaceprint(f"Strip: '{text.strip()}'")print(f"Left strip: '{text.lstrip()}'")print(f"Right strip: '{text.rstrip()}'")# Splitting and joiningwords ="apple,banana,cherry".split(",")print(f"Split: {words}")joined =" - ".join(words)print(f"Joined: {joined}")# Replacingreplaced ="Hello World".replace("World", "Python")print(f"Replaced: {replaced}")# Findingposition ="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 =25height =5.7# f-strings (recommended)print(f"My name is {name}, I'm {age} years old and {height} feet tall")# format() methodprint("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 numberspi =3.14159265print(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-1r1 =range(5)print(f"range(5): {list(r1)}")# range(start, stop) - from start to stop-1r2 =range(2, 8)print(f"range(2, 8): {list(r2)}")# range(start, stop, step) - with custom stepr3 =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 numbersevens =range(0, 20, 2)print(f"Even numbers: {list(evens)}")# Odd numbersodds =range(1, 20, 2)print(f"Odd numbers: {list(odds)}")
# Basic loopprint("Counting to 5:")for i inrange(1, 6):print(i, end=" ")print()# Loop with indexfruits = ["apple", "banana", "cherry"]print("\nFruits with index:")for i inrange(len(fruits)):print(f"{i}: {fruits[i]}")# Countdownprint("\nCountdown:")for i inrange(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 operationsr =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? {4in r}")print(f"Is 5 in range? {5in r}")print(f"Min: {min(r)}, Max: {max(r)}")# Slicing rangesprint(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 listshopping_list = []# Add itemsshopping_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 listif"milk"in shopping_list:print("Don't forget to buy milk!")# Remove an itemshopping_list.remove("bread")print(f"After removing bread: {shopping_list}")# Sort alphabeticallyshopping_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 statisticsscores = [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 studenttop_student =max(students, key=lambda x: x[1])print(f"\nTop student: {top_student[0]} with score {top_student[1]}")# Students above averageprint("\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 wordswords = text.lower().split()# Count total wordsprint(f"Total words: {len(words)}")# Count unique wordsunique_words =list(set(words))print(f"Unique words: {len(unique_words)}")# Count occurrences of a specific wordpython_count = words.count("python")print(f"'python' appears {python_count} times")# Find word positionsfor i, word inenumerate(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 10numbers =# 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 tuplepass# Test with a listdata = [10, 20, 30, 40, 50]# Unpack the resultsminimum, maximum, average = get_stats(data)# Print results
print("Multiples of 3 between 1 and 30:")for num inrange(3, 31, 3):print(num, end=" ")print()# Alternativemultiples =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
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!
---title: "Sequences"jupyter: python3---## Understanding Sequences in PythonSequences 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.## 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.```{python}# Examples of different sequence typesmy_list = [1, 2, 3, 4, 5] # List - mutablemy_tuple = (1, 2, 3, 4, 5) # Tuple - immutablemy_string ="Hello"# String - immutablemy_range =range(1, 6) # Range - immutableprint(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```## The `len()` FunctionThe `len()` function returns the number of items in a sequence.```{python}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))}")```## The `in` OperationThe `in` operator checks if an item exists in a sequence. It returns `True` or `False`.```{python}colors = ["red", "green", "blue", "yellow"]vowels ="aeiou"# Check if item is in listprint(f"Is 'red' in colors? {'red'in colors}")print(f"Is 'purple' in colors? {'purple'in colors}")# Check if character is in stringprint(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'notin colors}")```**Practical example:**```{python}# Check if user is adminadmin_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")```## IndexingIndexing allows you to access individual items in a sequence using their position.**Important:** Python uses **zero-based indexing** (first item is at index 0).```{python}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]}")```**Indexing visualization:**```{python}# Index: 0 1 2 3 4# Index: -5 -4 -3 -2 -1letters = ['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]}")```**Indexing strings:**```{python}message ="Python"print(f"First character: {message[0]}")print(f"Last character: {message[-1]}")print(f"Third character: {message[2]}")```## SlicingSlicing 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)```{python}numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]# Basic slicingprint(f"numbers[2:5] = {numbers[2:5]}") # Items at index 2, 3, 4print(f"numbers[0:3] = {numbers[0:3]}") # First three itemsprint(f"numbers[5:] = {numbers[5:]}") # From index 5 to endprint(f"numbers[:4] = {numbers[:4]}") # From beginning to index 3print(f"numbers[:] = {numbers[:]}") # Copy entire list```**Slicing with step:**```{python}numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]print(f"Every second item: {numbers[::2]}") # Step of 2print(f"Every third item: {numbers[::3]}") # Step of 3print(f"Reversed list: {numbers[::-1]}") # Negative step reversesprint(f"Every second item from 1 to 8: {numbers[1:8:2]}")```**Slicing strings:**```{python}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]}")```**Negative indices in slicing:**```{python}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]}")```## Lists - Mutable SequencesLists are **mutable** (changeable) sequences that can store any type of data.### Creating Lists {.unnumbered}```{python}# Different ways to create listsempty_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() constructorfrom_string =list("Python")from_range =list(range(5))print(f"From string: {from_string}")print(f"From range: {from_range}")```### Adding Items to Lists {.unnumbered}```{python}# append() - adds one item to the endfruits = ["apple", "banana"]fruits.append("cherry")print(f"After append: {fruits}")# extend() - adds multiple itemsfruits.extend(["date", "elderberry"])print(f"After extend: {fruits}")# insert() - adds item at specific positionfruits.insert(1, "apricot") # Insert at index 1print(f"After insert: {fruits}")# Using + operatormore_fruits = fruits + ["fig", "grape"]print(f"Using + operator: {more_fruits}")```### Removing Items from Lists {.unnumbered}```{python}numbers = [1, 2, 3, 4, 5, 3, 6, 7]# remove() - removes first occurrence of valuenumbers_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 slicenumbers_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 itemsnumbers_copy = numbers.copy()numbers_copy.clear()print(f"After clear(): {numbers_copy}")```### Modifying Lists {.unnumbered}```{python}# Lists are mutable - you can change itemscolors = ["red", "green", "blue"]colors[1] ="yellow"# Change second itemprint(f"Modified list: {colors}")# Change multiple items with slicingnumbers = [0, 1, 2, 3, 4, 5]numbers[1:4] = [10, 20, 30]print(f"After slice assignment: {numbers}")```### Sorting Lists {.unnumbered}```{python}# sort() - sorts the list in placenumbers = [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 listoriginal = [3, 1, 4, 1, 5, 9, 2, 6]sorted_list =sorted(original)print(f"Original: {original}")print(f"Sorted copy: {sorted_list}")# Sorting stringswords = ["banana", "apple", "cherry", "date"]words.sort()print(f"Sorted words: {words}")# Case-insensitive sortingmixed_case = ["banana", "Apple", "cherry", "Date"]mixed_case.sort(key=str.lower)print(f"Case-insensitive sort: {mixed_case}")```**Other useful list methods:**```{python}numbers = [1, 2, 3, 2, 4, 2, 5]# count() - counts occurrencesprint(f"Count of 2: {numbers.count(2)}")# index() - finds first occurrenceprint(f"Index of 3: {numbers.index(3)}")# reverse() - reverses the list in placenumbers.reverse()print(f"Reversed: {numbers}")```## Tuples - Immutable SequencesTuples are **immutable** (unchangeable) sequences. Once created, you cannot modify, add, or remove items.### Creating Tuples {.unnumbered}```{python}# Different ways to create tuplesempty_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 optionalprint(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() constructorfrom_list =tuple([1, 2, 3])from_string =tuple("Python")print(f"From list: {from_list}")print(f"From string: {from_string}")```### Why Use Tuples? {.unnumbered}```{python}## 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 functionscoordinates = (10, 20) # Coordinates shouldn't changergb_color = (255, 0, 128) # Color values are fixedprint(f"Coordinates: {coordinates}")print(f"RGB Color: {rgb_color}")# Trying to modify a tuple causes an error# coordinates[0] = 15 # This would raise: TypeError```### Tuple Operations {.unnumbered}```{python}# Tuples support indexing, slicing, and other sequence operationsnumbers = (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() methodsvalues = (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 repetitiontuple1 = (1, 2, 3)tuple2 = (4, 5, 6)combined = tuple1 + tuple2repeated = tuple1 *3print(f"Combined: {combined}")print(f"Repeated: {repeated}")```## Lists vs Tuples: Key Differences```{python}# Create a list and a tuple with same valuesmy_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={3in my_list}, 3 in tuple={3in my_tuple}")print("\nDifferences:")print(f"List is mutable: {my_list}")my_list[0] =100print(f"After modification: {my_list}")print(f"\nTuple is immutable: {my_tuple}")# my_tuple[0] = 100 # This would raise TypeErrorprint("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 ✓ |## Math Operations on Sequences```{python}numbers = [1, 2, 3, 4, 5]tuple_nums = (10, 20, 30, 40, 50)# Sum of all itemsprint(f"Sum of list: {sum(numbers)}")print(f"Sum of tuple: {sum(tuple_nums)}")# Minimum and maximumprint(f"Min: {min(numbers)}, Max: {max(numbers)}")# Lengthprint(f"Length: {len(numbers)}")# Concatenationlist1 = [1, 2, 3]list2 = [4, 5, 6]combined = list1 + list2print(f"Concatenated: {combined}")# Repetitionrepeated = [1, 2] *3print(f"Repeated: {repeated}")# Membershipprint(f"Is 3 in numbers? {3in numbers}")```**Working with numeric sequences:**```{python}scores = [85, 92, 78, 90, 88]total =sum(scores)count =len(scores)average = total / counthighest =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}")```## Unpacking SequencesUnpacking allows you to assign sequence items to multiple variables in one line.### Basic Unpacking {.unnumbered}```{python}# Unpacking a listcoordinates = [10, 20]x, y = coordinatesprint(f"x = {x}, y = {y}")# Unpacking a tupleperson = ("Alice", 25, "New York")name, age, city = personprint(f"Name: {name}, Age: {age}, City: {city}")# Unpacking a stringcode ="RGB"r, g, b = codeprint(f"r={r}, g={g}, b={b}")```### Extended Unpacking with * {.unnumbered}```{python}# Using * to capture multiple valuesnumbers = [1, 2, 3, 4, 5, 6]# Get first, last, and everything in betweenfirst, *middle, last = numbersprint(f"First: {first}")print(f"Middle: {middle}")print(f"Last: {last}")# Get first two and the restfirst, second, *rest = numbersprint(f"First: {first}, Second: {second}, Rest: {rest}")# Get all but the last*most, last = numbersprint(f"Most: {most}, Last: {last}")```### Swapping Values {.unnumbered}```{python}# Easy value swapping with unpackinga =5b =10print(f"Before swap: a={a}, b={b}")a, b = b, aprint(f"After swap: a={a}, b={b}")# Rotating valuesx, y, z =1, 2, 3print(f"Before rotation: x={x}, y={y}, z={z}")x, y, z = z, x, yprint(f"After rotation: x={x}, y={y}, z={z}")```### Unpacking in Loops {.unnumbered}```{python}# Unpacking tuples in a looppeople = [ ("Alice", 25), ("Bob", 30), ("Charlie", 35)]for name, age in people:print(f"{name} is {age} years old")# Unpacking with enumeratefruits = ["apple", "banana", "cherry"]for index, fruit inenumerate(fruits):print(f"{index}: {fruit}")```## Strings as SequencesStrings are **immutable** sequences of characters.### String Operations {.unnumbered}```{python}message ="Python Programming"# Indexingprint(f"First character: {message[0]}")print(f"Last character: {message[-1]}")# Slicingprint(f"First word: {message[:6]}")print(f"Second word: {message[7:]}")print(f"Every other character: {message[::2]}")# Lengthprint(f"Length: {len(message)}")# Membershipprint(f"'Python' in message: {'Python'in message}")print(f"'Java' in message: {'Java'in message}")# Iterationprint("Characters:", end=" ")for char in message[:6]:print(char, end=" ")print()```### String Methods {.unnumbered}```{python}text =" Hello, World! "# Case conversionprint(f"Upper: {text.upper()}")print(f"Lower: {text.lower()}")print(f"Title: {text.title()}")# Removing whitespaceprint(f"Strip: '{text.strip()}'")print(f"Left strip: '{text.lstrip()}'")print(f"Right strip: '{text.rstrip()}'")# Splitting and joiningwords ="apple,banana,cherry".split(",")print(f"Split: {words}")joined =" - ".join(words)print(f"Joined: {joined}")# Replacingreplaced ="Hello World".replace("World", "Python")print(f"Replaced: {replaced}")# Findingposition ="Hello World".find("World")print(f"Position of 'World': {position}")```### String Formatting {.unnumbered}```{python}name ="Alice"age =25height =5.7# f-strings (recommended)print(f"My name is {name}, I'm {age} years old and {height} feet tall")# format() methodprint("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 numberspi =3.14159265print(f"Pi rounded to 2 decimals: {pi:.2f}")print(f"Pi rounded to 4 decimals: {pi:.4f}")```## RangesRanges represent immutable sequences of numbers, commonly used in loops.### Creating Ranges {.unnumbered}```{python}# range(stop) - from 0 to stop-1r1 =range(5)print(f"range(5): {list(r1)}")# range(start, stop) - from start to stop-1r2 =range(2, 8)print(f"range(2, 8): {list(r2)}")# range(start, stop, step) - with custom stepr3 =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 numbersevens =range(0, 20, 2)print(f"Even numbers: {list(evens)}")# Odd numbersodds =range(1, 20, 2)print(f"Odd numbers: {list(odds)}")```### Using Ranges in Loops {.unnumbered}```{python}# Basic loopprint("Counting to 5:")for i inrange(1, 6):print(i, end=" ")print()# Loop with indexfruits = ["apple", "banana", "cherry"]print("\nFruits with index:")for i inrange(len(fruits)):print(f"{i}: {fruits[i]}")# Countdownprint("\nCountdown:")for i inrange(5, 0, -1):print(i, end=" ")print("Blast off!")```### Range Operations {.unnumbered}```{python}# Ranges support sequence operationsr =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? {4in r}")print(f"Is 5 in range? {5in r}")print(f"Min: {min(r)}, Max: {max(r)}")# Slicing rangesprint(f"Slice [1:4]: {list(r[1:4])}")```## Practical Examples### Example 1: Managing a Shopping List {.unnumbered}```{python}# Create shopping listshopping_list = []# Add itemsshopping_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 listif"milk"in shopping_list:print("Don't forget to buy milk!")# Remove an itemshopping_list.remove("bread")print(f"After removing bread: {shopping_list}")# Sort alphabeticallyshopping_list.sort()print(f"Sorted list: {shopping_list}")```### Example 2: Processing Student Grades {.unnumbered}```{python}# Student grades (name, score)students = [ ("Alice", 95), ("Bob", 87), ("Charlie", 92), ("Diana", 88), ("Eve", 91)]# Calculate statisticsscores = [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 studenttop_student =max(students, key=lambda x: x[1])print(f"\nTop student: {top_student[0]} with score {top_student[1]}")# Students above averageprint("\nStudents above average:")for name, score in students:if score > average:print(f" {name}: {score}")```### Example 3: Text Analysis {.unnumbered}```{python}text ="Python is amazing and Python is powerful"# Convert to lowercase and split into wordswords = text.lower().split()# Count total wordsprint(f"Total words: {len(words)}")# Count unique wordsunique_words =list(set(words))print(f"Unique words: {len(unique_words)}")# Count occurrences of a specific wordpython_count = words.count("python")print(f"'python' appears {python_count} times")# Find word positionsfor i, word inenumerate(words):if word =="python":print(f"'python' found at position {i}")```## Practice Exercises### Exercise 1: List Manipulation {.unnumbered}Create a list of numbers and perform various operations:```{python}#| eval: false# Create a list of numbers from 1 to 10numbers =# Add 11 and 12 to the end# Remove the number 5# Insert 100 at index 3# Print the final list```### Exercise 2: Tuple Unpacking {.unnumbered}Create a function that returns multiple values:```{python}#| eval: falsedef get_stats(numbers):# Return min, max, and average as a tuplepass# Test with a listdata = [10, 20, 30, 40, 50]# Unpack the resultsminimum, maximum, average = get_stats(data)# Print results```### Exercise 3: String Slicing {.unnumbered}Extract parts of an email address:```{python}#| eval: falseemail ="user.name@example.com"# Extract username (before @)username =# Extract domain (after @)domain =# Print both```### Exercise 4: Working with Ranges {.unnumbered}Print all multiples of 3 between 1 and 30:```{python}#| eval: false# Use range to generate multiples of 3```## Solutions### Solution 1: {.unnumbered}```{python}#| code-fold: true#| code-summary: "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}")```### Solution 2: {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"def get_stats(numbers):returnmin(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}")```### Solution 3: {.unnumbered}```{python}#| code-fold: true#| code-summary: "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 splitusername, domain = email.split('@')print(f"\nUsing split - Username: {username}, Domain: {domain}")```### Solution 4: {.unnumbered}```{python}#| code-fold: true#| code-summary: "Click to show solution"print("Multiples of 3 between 1 and 30:")for num inrange(3, 31, 3):print(num, end=" ")print()# Alternativemultiples =list(range(3, 31, 3))print(f"\nAs a list: {multiples}")```## Summary: When to Use Each Sequence Type### Lists {.unnumbered}- **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 {.unnumbered}- **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 {.unnumbered}- **Use when**: Working with text data- **Examples**: Names, messages, file contents, user input- **Key feature**: Immutable sequence of characters### Ranges {.unnumbered}- **Use when**: Need sequence of numbers, especially in loops- **Examples**: Loop iterations, number sequences, indexing- **Key feature**: Memory-efficient, immutable## 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## Next StepsNow 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!