Python Lists
Master ordered, mutable collections in Python
📋 Understanding Lists
Lists are ordered, mutable collections that can store multiple items. They're one of the most versatile and commonly used data types in Python.
# Creating and using lists
fruits = ["apple", "banana", "orange"] # List of strings
numbers = [1, 2, 3, 4, 5] # List of integers
mixed = [1, "hello", 3.14, True] # List different types
empty = [] # Empty list
# Accessing list elements
print(fruits[0]) # First element: "apple"
print(numbers[-1]) # Last element: 5
Ordered
Collection
Mutable
Changeable
Indexed
Access
🔹 Creating Lists
List Creation Examples
# Empty list
empty_list = []
print(empty_list) # []
# List with items
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
# Using list() constructor
colors = list(["red", "green", "blue"])
print(colors) # ['red', 'green', 'blue']
Accessing List Items
Index Access
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
Slicing
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # [2, 3, 4]
print(numbers[:3]) # [1, 2, 3]
print(numbers[2:]) # [3, 4, 5]
Modifying Lists
Adding and Removing Items
fruits = ["apple", "banana"]
# Adding items
fruits.append("cherry") # Add to end
fruits.insert(1, "orange") # Insert at index 1
fruits.extend(["grape", "kiwi"]) # Add multiple items
print(fruits) # ['apple', 'orange', 'banana', 'cherry', 'grape', 'kiwi']
# Removing items
fruits.remove("banana") # Remove by value
popped = fruits.pop() # Remove last item
del fruits[0] # Remove by index
print(fruits) # ['orange', 'cherry', 'grape']
Common List Methods
Essential List Methods
numbers = [3, 1, 4, 1, 5, 9, 2]
# Sorting and reversing
numbers.sort() # Sort in place
print(numbers) # [1, 1, 2, 3, 4, 5, 9]
numbers.reverse() # Reverse in place
print(numbers) # [9, 5, 4, 3, 2, 1, 1]
# Counting and finding
count = numbers.count(1) # Count occurrences
index = numbers.index(5) # Find index of value
print(f"Count of 1: {count}") # Count of 1: 2
print(f"Index of 5: {index}") # Index of 5: 1
# Length and membership
print(len(numbers)) # 7
print(5 in numbers) # True
List Comprehensions
Creating Lists with Comprehensions
# Basic list comprehension
squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
# With condition
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# String manipulation
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
Real-World Example: Shopping Cart
Shopping Cart Implementation
# Shopping cart using lists
cart = []
prices = {"apple": 0.5, "banana": 0.3, "orange": 0.8}
# Add items to cart
cart.append("apple")
cart.append("banana")
cart.extend(["orange", "apple"])
print(f"Cart: {cart}")
# Calculate total
total = sum(prices[item] for item in cart)
print(f"Total: ${total:.2f}")
# Count items
from collections import Counter
item_counts = Counter(cart)
print("Items in cart:")
for item, count in item_counts.items():
print(f" {item}: {count} x ${prices[item]} = ${count * prices[item]:.2f}")
# Output:
# Cart: ['apple', 'banana', 'orange', 'apple']
# Total: $2.10
🏋️ Practice Exercise: Grade Manager
Create a program that manages student grades using lists. Include functions to add grades, calculate average, and find highest/lowest grades.
Solution Template
# Grade Manager
grades = []
def add_grade(grade):
if 0 <= grade <= 100:
grades.append(grade)
print(f"Added grade: {grade}")
else:
print("Grade must be between 0 and 100")
def calculate_average():
if grades:
return sum(grades) / len(grades)
return 0
def get_grade_stats():
if not grades:
return "No grades available"
avg = calculate_average()
highest = max(grades)
lowest = min(grades)
return f"Average: {avg:.1f}, Highest: {highest}, Lowest: {lowest}"
# Test the functions
add_grade(85)
add_grade(92)
add_grade(78)
print(f"Grades: {grades}")
print(get_grade_stats())