Coding Concept - Lists
Understanding Lists in Python and JavaScript
%%js
// Popcorn Hack 1: Initialize Snake
// ===============================
// TODO: Make an array called snake with:
// - 1 head ("H")
// - 3 body segments ("B")
// - 1 tail ("T")
// Hint: arrays in JavaScript use [ ... ] with commas.
let snake = ["H", "B", "B", "B", "T"]; // <-- fill this in
console.log("Starting snake:", snake);
// ===============================
// Popcorn Hack 2: Growing the Snake
// ===============================
// - Add 2 tails ("T") to the END of the array
// - Use push() twice
// Example: snake.push("T")
// Your code here
snake.push("T");
snake.push("T");
console.log("Snake after eating:", snake);
// ===============================
// Popcorn Hack 3: Snake Loses a Tail
// ===============================
// TODO: The snake moves forward, tail disappears
// - Remove the LAST 2 elements
// - Use pop() twice
// Example: snake.pop()
// Your code here
snake.pop();
snake.pop();
console.log("Snake after losing tails:", snake);
// ===============================
// Popcorn Hack 4: Combining It All
// ===============================
// TODO:
// Step 1: Add 2 new heads ("H") to the START of the array
// Step 2: Remove 1 head from the START of the array
// Step 3: Print the new snake and its first head
// Your code here
snake.unshift("H");
snake.unshift("H");
snake.shift();
console.log("Snake after moving:", snake);
console.log("New first head is:", snake[0]);
// ===============================
// Check Your Understanding
// ===============================
// Start fresh with a new snake
// Your code here
snake = ["H", "B", "B", "T"];
snake.unshift("H");
snake.push("T");
snake.splice(2, 1);
console.log("Final snake:", snake);
console.log("First head:", snake[0]);
console.log("Last element:", snake[snake.length - 1]);
<IPython.core.display.Javascript object>