Table of Contents
Introduction to Lists
Working with Lists
Introduction to Tuples
Working with Tuples
Lists vs Tuples
Exercises
Final Project
1. Introduction to Lists
A list is a collection of items in Python that is ordered, changeable (mutable), and allows duplicate values. Lists are one of the most versatile and commonly used data structures in Python.
Creating Lists
empty_list = []
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
duplicates = [1, 2, 2, 3, 3, 3]
nested = [[1, 2], [3, 4], [5, 6]]
converted = list("hello")
2. Working with Lists
Accessing List Elements
Lists use zero-based indexing, meaning the first element is at index 0.
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
print(fruits[0])
print(fruits[2])
print(fruits[-1])
print(fruits[-2])
Slicing Lists
Slicing allows you to get a portion of a list using the syntax [start:stop:step].
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])
print(numbers[:4])
print(numbers[5:])
print(numbers[:])
print(numbers[::2])
print(numbers[1::2])
print(numbers[::-1])
print(numbers[-5:-2])
Modifying Lists
Lists are mutable, so you can change their contents.
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)
numbers = [1, 2, 3, 4, 5]
numbers[1:4] = [20, 30, 40]
print(numbers)
numbers[1:3] = [100]
print(numbers)
Adding Elements to Lists
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
fruits.insert(1, "apricot")
print(fruits)
fruits.extend(["date", "elderberry"])
print(fruits)
more_fruits = fruits + ["fig", "grape"]
print(more_fruits)
repeated = ["x"] * 5
print(repeated)
Removing Elements from Lists
fruits = ["apple", "banana", "cherry", "date", "banana"]
fruits.remove("banana")
print(fruits)
last_fruit = fruits.pop()
print(last_fruit)
print(fruits)
second_fruit = fruits.pop(1)
print(second_fruit)
print(fruits)
numbers = [1, 2, 3, 4, 5]
del numbers[2]
print(numbers)
del numbers[1:3]
print(numbers)
numbers.clear()
print(numbers)
List Methods
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
print(numbers.count(1))
print(numbers.count(5))
print(numbers.index(4))
print(numbers.index(5))
numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)
original = [3, 1, 4, 1, 5]
sorted_list = sorted(original)
print(original)
print(sorted_list)
fruits = ["apple", "banana", "cherry"]
fruits.reverse()
print(fruits)
original = [1, 2, 3]
copied = original.copy()
copied[0] = 100
print(original)
print(copied)
List Operations and Functions
numbers = [1, 2, 3, 4, 5]
print(len(numbers))
print(3 in numbers)
print(10 in numbers)
print(10 not in numbers)
print(sum(numbers))
print(min(numbers))
print(max(numbers))
for num in numbers:
print(num)
for i, num in enumerate(numbers):
print(f"Index {i}: {num}")
Nested Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(matrix[0])
print(matrix[1][2])
for row in matrix:
for element in row:
print(element, end=" ")
print()
3. Introduction to Tuples
A tuple is a collection in Python that is ordered and unchangeable (immutable). Tuples are written with round brackets.
Creating Tuples
empty_tuple = ()
numbers = (1, 2, 3, 4, 5)
fruits = ("apple", "banana", "cherry")
mixed = (1, "hello", 3.14, True)
single = (5,)
not_tuple = (5)
coordinates = 10, 20, 30
print(type(coordinates))
converted = tuple([1, 2, 3])
from_string = tuple("hello")
nested = ((1, 2), (3, 4), (5, 6))
4. Working with Tuples
Accessing Tuple Elements
Tuples use the same indexing and slicing as lists.
fruits = ("apple", "banana", "cherry", "date", "elderberry")
print(fruits[0])
print(fruits[-1])
print(fruits[1:4])
print(fruits[:3])
print(fruits[::2])
Tuple Immutability
Once a tuple is created, you cannot change, add, or remove elements.
numbers = (1, 2, 3, 4, 5)
mixed = ([1, 2, 3], "hello", 5)
mixed[0][0] = 100
print(mixed)
new_numbers = numbers + (6, 7, 8)
print(new_numbers)
Tuple Methods
Tuples have only two methods because they are immutable.
numbers = (1, 2, 3, 2, 4, 2, 5)
print(numbers.count(2))
print(numbers.index(4))
print(numbers.index(2))
Tuple Operations
numbers = (1, 2, 3, 4, 5)
print(len(numbers))
print(3 in numbers)
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2
print(combined)
repeated = (1, 2) * 3
print(repeated)
print(sum(numbers))
print(min(numbers))
print(max(numbers))
for num in numbers:
print(num)
Tuple Unpacking
coordinates = (10, 20, 30)
x, y, z = coordinates
print(x)
print(y)
print(z)
numbers = (1, 2, 3, 4, 5)
first, *middle, last = numbers
print(first)
print(middle)
print(last)
a = 5
b = 10
a, b = b, a
print(a)
print(b)
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers)
minimum, maximum, total = get_stats([1, 2, 3, 4, 5])
print(minimum, maximum, total)
5. Lists vs Tuples
Key Differences
| Feature | List | Tuple |
| Syntax | Square brackets [] | Parentheses () |
| Mutability | Mutable (can change) | Immutable (cannot change) |
| Performance | Slower | Faster |
| Methods | Many methods | Only 2 methods (count, index) |
| Use Case | When you need to modify data | When data shouldn't change |
| Memory | Uses more memory | Uses less memory |
When to Use Lists
When you need to modify the collection (add, remove, change elements)
When you're working with data that will change over time
When you need methods like append, remove, sort, etc.
cart = ["apple", "banana"]
cart.append("orange")
cart.remove("banana")
When to Use Tuples
When you have data that shouldn't change (coordinates, RGB colors, etc.)
When you want to use the collection as a dictionary key (must be immutable)
For better performance and memory efficiency
To prevent accidental modification of data
position = (10, 20)
red = (255, 0, 0)
locations = {
(0, 0): "origin",
(10, 20): "point A"
}
Converting Between Lists and Tuples
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple)
my_tuple = (4, 5, 6)
my_list = list(my_tuple)
print(my_list)
6. Exercises
Exercise 1: Basic List Operations
Create a list of your five favorite movies. Then:
Exercise 2: List Slicing
Given the list numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
Extract the first 5 numbers
Extract the last 3 numbers
Extract every second number
Reverse the entire list using slicing
Exercise 3: List Comprehension
Create a list of squares of numbers from 1 to 10 using list comprehension
Create a list of even numbers from 1 to 20 using list comprehension
Create a list of all words longer than 3 characters from: ["cat", "elephant", "dog", "butterfly", "ant"]
Exercise 4: Nested Lists
Create a 3x3 matrix (2D list) with numbers 1-9. Then:
Exercise 5: Tuple Operations
Create a tuple with the days of the week. Then:
Print the first day
Print the last day
Check if "Friday" is in the tuple
Count how many times "Monday" appears
Try to change the first element (and observe the error)
Exercise 6: Tuple Unpacking
Create a function that takes a list of numbers and returns a tuple containing:
The minimum value
The maximum value
The average value
Use tuple unpacking to assign these values to separate variables.
Exercise 7: List Sorting
Given the list scores = [85, 92, 78, 90, 88, 76, 95, 89]:
Exercise 8: Working with Strings as Lists
Given the string sentence = "Python is awesome":
Convert it to a list of words
Reverse the order of words
Join them back into a string
Convert the string to a list of characters and remove all vowels
Exercise 9: Advanced Challenge
Create a program that:
Takes a list of student names and their scores as tuples: [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
Sorts the students by their scores in descending order
Prints the top student's name and score
Calculates the average score
Creates two separate lists: one with names and one with scores
7. Final Project: Task Manager
Create a task management system that uses both lists and tuples. The program should:
Requirements:
Task Structure: Each task should be stored as a tuple with:
Task ID (integer)
Task description (string)
Priority (string: "high", "medium", "low")
Status (string: "pending" or "completed")
Features to Implement:
Add a new task
View all tasks
View tasks by priority
Mark a task as completed
Delete a task
View only pending tasks
View only completed tasks
Sort tasks by priority
Display statistics (total tasks, completed tasks, pending tasks)
Menu System: Create a text-based menu that allows users to choose operations
Example Output:
=== Task Manager ===
1. Add Task
2. View All Tasks
3. View Tasks by Priority
4. Mark Task as Completed
5. Delete Task
6. View Pending Tasks
7. View Completed Tasks
8. View Statistics
9. Exit
Enter your choice: 1
Enter task description: Complete Python tutorial
Enter priority (high/medium/low): high
Task added successfully!
Task ID: 1, Description: Complete Python tutorial, Priority: high, Status: pending
Starter Code Structure:
tasks = []
task_id_counter = 1
def add_task():
pass
def view_all_tasks():
pass
def view_by_priority():
pass
def mark_completed():
pass
def delete_task():
pass
def view_pending():
pass
def view_completed():
pass
def show_statistics():
pass
def main():
while True:
print("\n=== Task Manager ===")
print("1. Add Task")
print("2. View All Tasks")
print("3. View Tasks by Priority")
print("4. Mark Task as Completed")
print("5. Delete Task")
print("6. View Pending Tasks")
print("7. View Completed Tasks")
print("8. View Statistics")
print("9. Exit")
choice = input("\nEnter your choice: ")
if __name__ == "__main__":
main()
Bonus Challenges:
Add the ability to edit a task's description or priority
Add a search function to find tasks by keyword
Save tasks to a file and load them when the program starts
Add due dates to tasks (stored as part of the tuple)
Sort tasks by multiple criteria (priority and status)
Practice Tips
Type along: Don't just read the code - type it yourself and run it
Experiment: Modify the examples and see what happens
Break things: Try to cause errors intentionally to understand error messages
Use print(): Print variables frequently to see what's happening
Comment your code: Explain what each section does
Practice daily: Spend 30 minutes daily working with lists and tuples
Build mini-projects: Create small programs like a shopping list, grade calculator, etc.
Additional Resources for Learning
Once you're comfortable with lists and tuples:
Learn about dictionaries and sets (other Python data structures)
Explore more advanced list comprehensions
Study time and space complexity of different operations
Practice with coding challenges on platforms like LeetCode or HackerRank
Good luck with your Python journey! Remember, programming is learned by doing, so make sure to complete the exercises and the final project. Happy coding!