Coding Concept - Lists
Understanding Lists in Python and JavaScript
# -------------------------------
# Popcorn Hack 1: Initialize Snake
# -------------------------------
# TODO: Create a list with 1 head, 3 body segments, and 1 tail
# Example shape: ["H", "B", "B", "B", "T"]
snake = ["H", "B", "B", "B", "T"] # <-- fill in here
print("Starting snake:", snake)
# -------------------------------
# Popcorn Hack 2: Growing the Snake
# -------------------------------
# TODO: Append 2 tails ("T") to the end of the snake list
# Use append() twice
# snake.append(...)
# snake.append(...)
snake.append("T")
snake.append("T")
print("Snake after eating:", snake)
# -------------------------------
# Popcorn Hack 3: Snake Loses a Tail
# -------------------------------
# TODO: Remove the last 2 elements from the snake list
# Use del with negative indexing (ex: del snake[-1])
# del snake[...]
# del snake[...]
del snake[-1]
del snake[-1]
print("Snake after losing tails:", snake)
# -------------------------------
# Popcorn Hack 4: Combining It All
# -------------------------------
# TODO:
# Step 1: Add 2 new heads at the start (use insert(0, ...))
# Step 2: Remove 1 head from the start (use del snake[0])
# Step 3: Print new snake and its first head
# snake.insert(0, "H")
# snake.insert(0, "H")
# del snake[0]
snake.insert(0, "H")
snake.insert(0, "H")
del snake[0]
print("Snake after moving:", snake)
print("New first head is:", snake[0])
# -------------------------------
# Check Your Understanding
# -------------------------------
snake = ["H", "B", "B", "T"]
snake.insert(0, "H")
snake.append("T")
del snake[2]
print("Final snake:", snake)
print("First head:", snake[0])
print("Last element:", snake[-1])
Starting snake: ['H', 'B', 'B', 'B', 'T']
Snake after eating: ['H', 'B', 'B', 'B', 'T', 'T', 'T']
Snake after losing tails: ['H', 'B', 'B', 'B', 'T']
Snake after moving: ['H', 'H', 'B', 'B', 'B', 'T']
New first head is: H
Final snake: ['H', 'H', 'B', 'T', 'T']
First head: H
Last element: T