- ๐ผ๏ธ Example 1: Basic Image Processing (Pixel Manipulation)
Imagine a simplified grayscale image as a list of lists, where each inner list represents a row of pixel intensities (0-255).
image = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
# Invert the image (255 - pixel_value) using list comprehension
inverted_image = [[255 - pixel for pixel in row] for row in image]
print(inverted_image) # Output: [[245, 235, 225], [215, 205, 195], [185, 175, 165]]
# Change a specific pixel to black (0)
image[1][1] = 0
print(image) # Output: [[10, 20, 30], [40, 0, 60], [70, 80, 90]]
- ๐ฎ Example 2: Game Board State Management (Tic-Tac-Toe)
Represent a Tic-Tac-Toe board and update moves.
board = [
[' ', ' ', ' '],
[' ', ' ', ' '],
[' ', ' ', ' ']
]
# Player 'X' makes a move
row = 1
col = 0
board[row][col] = 'X'
print(board) # Output: [[' ', ' ', ' '], ['X', ' ', ' '], [' ', ' ', ' ']]
# Check if a specific row is all 'X' (simplified)
def check_win_row(player, current_board):
for r in current_board:
if all(cell == player for cell in r):
return True
return False
print(check_win_row('X', board)) # Output: False
- ๐ Example 3: Data Analysis (Filtering & Transformation)
Process a list of student scores.
scores = [85, 92, 78, 65, 95, 70]
# Filter out scores below 75 (passing scores)
passing_scores = [score for score in scores if score >= 75]
print(passing_scores) # Output: [85, 92, 78, 95]
# Apply a 5-point curve to all scores
curved_scores = [min(100, score + 5) for score in scores] # Cap at 100
print(curved_scores) # Output: [90, 97, 83, 70, 100, 75]
- ๐ Example 4: Simulating a Queue or Stack
Lists can easily mimic these fundamental data structures.
# As a Queue (FIFO - First In, First Out)
queue = []
queue.append("Task A") # Enqueue
queue.append("Task B") # Enqueue
print(queue.pop(0)) # Dequeue: Output: Task A
print(queue) # Output: ['Task B']
# As a Stack (LIFO - Last In, First Out)
stack = []
stack.append("Page 1") # Push
stack.append("Page 2") # Push
print(stack.pop()) # Pop: Output: Page 2
print(stack) # Output: ['Page 1']