zuai-logo

Lists

David Foster

David Foster

7 min read

Listen to this study note

Study Guide Overview

This study guide covers list operations in AP Computer Science Principles, focusing on basic operations, adding and removing elements, and looping. Key concepts include accessing elements by index, assigning values, inserting/appending/removing elements, determining list length, complete/partial traversal using for and while loops, and linear search. It also provides exam tips, focusing on common question types and high-priority topics like list traversal and modification, along with practice questions covering these concepts.

AP Computer Science Principles: List Operations - The Night Before 🚀

Hey! Let's get you prepped for the AP CSP exam with a super-focused review of list operations. We'll make sure you're not just memorizing, but understanding how lists work. Let's dive in!

Basic List Operations

Lists are fundamental in programming, and they're a big deal on the AP exam. Remember, AP Pseudocode starts indexing at 1, but in most programming languages like Python, it starts at 0. Keep this in mind to avoid common mistakes!

Key Concept

Accessing Elements by Index

Think of a list like a set of numbered mailboxes. To get something from a specific box, you use its number (the index).

markdown-image

  • How it works: list_name[index]
  • Example:

python grocery_list = ["milk", "eggs", "cheese"] print(grocery_list[0]) # Output: milk


### 
<div data-custom-tag="key_point"> 

Assigning Element Values

</div>

#### Assigning to a Variable

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_c6ae50_520.png?alt=media&token=a16b04a1-200a-41bd-a044-91f4619284dd)

- You can grab an element from a list and store it in a variable.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] change = "soap" grocery_list[2] = change print(grocery_list) # Output: ["milk", "eggs", "soap"]


#### Assigning a Value Directly

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_9c2d56_1975.png?alt=media&token=5e5ce976-66a5-4657-ba7b-f56206ff0191)

- You can directly change the value of an element at a specific index.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] grocery_list[2] = "fish" print(grocery_list) # Output: ["milk", "eggs", "fish"]


#### Assigning One Element to Another

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_893a7c_1055.png?alt=media&token=5040c704-7717-4ef9-a3c5-e64be93b0644)

- You can copy the value of one element to another.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] grocery_list[0] = grocery_list[2] print(grocery_list) # Output: ["cheese", "eggs", "cheese"]


<div data-custom-tag="memory_aid"> 

**Visualize**: Think of list elements as items in a row. You can pick them out by their position (index) and swap them around.

</div>

##  Adding and Removing Elements 

Lists aren't static; you can add and remove items as needed. Here's how:

### Inserting Elements

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_e22653_1585.png?alt=media&token=34f181f3-0b95-4bae-ad53-70376930fe63)

- **How it works:** `list_name.insert(index, value)`
- Inserts a `value` at the specified `index`, shifting existing elements to the right.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] grocery_list.insert(2, "butter") print(grocery_list) # Output: ["milk", "eggs", "butter", "cheese"]


### Adding to the End (Appending)

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_053a3d_3896.png?alt=media&token=d1f7026a-6e4c-49db-b9fd-c41b8ff157a8)

- **How it works:** `list_name.append(value)`
- Adds a `value` to the very end of the list.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] grocery_list.append("flour") print(grocery_list) # Output: ["milk", "eggs", "cheese", "flour"]


### Removing Elements

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_c9f838_430.png?alt=media&token=9904c81f-8db5-48dc-a230-bc6a639cf7f6)

- **How it works:** `list_name.remove(value)`
- Removes the first occurrence of a `value` from the list.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] grocery_list.remove("eggs") print(grocery_list) # Output: ["milk", "cheese"]


### Determining List Length

![](https://zupay.blob.core.windows.net/resources/files/0baca4f69800419293b4c75aa2870acd_528d94_1075.png?alt=media&token=cd830cee-a81b-4ed8-bad2-0f8cbeac3824)

- **How it works:** `len(list_name)`
- Returns the number of elements in the list.
- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] print(len(grocery_list)) # Output: 3


<div data-custom-tag="memory_aid"> 

**Think of a train:**
- `insert()`: Adds a car in the middle of the train.
- `append()`: Adds a car at the end of the train.
- `remove()`: Takes away a specific car.
- `len()`: Counts the total number of cars.

</div>

##  Looping Through Lists 

Looping lets you go through each item in a list, one by one. This is super useful for many tasks!

### Complete Traversal

Going through every single element in the list.

#### Using a `for` Loop

- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] for element in grocery_list: print(element)

Output:

milk

eggs

cheese


#### Using a `while` Loop

- **Example:**

python grocery_list = ["milk", "eggs", "cheese"] i = 0 while i < len(grocery_list): print(grocery_list[i]) i += 1

Output:

milk

eggs

cheese


### Partial Traversal

Going through only a part of the list.

#### Using a `for` Loop

- **Example:**

python grocery_list = ["milk", "eggs", "cheese", "apples"] start_index = 1 end_index = 3 for i in range(start_index, end_index + 1): print(grocery_list[i])

Output:

eggs

cheese

apples


#### Using a `while` Loop

- **Example:**

python grocery_list = ["milk", "eggs", "cheese", "apples"] i = 1 while i < 4: print(grocery_list[i]) i += 1

Output:

eggs

cheese

apples


<div data-custom-tag="memory_aid"> 

**Think of a tour guide:**
- **Complete Traversal:** The guide shows you *every* stop on the tour.
- **Partial Traversal:** The guide only shows you *some* stops.

</div>

### 
<div data-custom-tag="quick_fact"> 

Linear Search

</div>

- Linear search (or sequential search) checks each element one by one until the desired element is found. It's simple but not the most efficient for large lists.

## 
<div data-custom-tag="exam_tip"> 

Final Exam Focus

</div>

- **High-Priority Topics:**
- List traversal (both complete and partial) using loops.
- Modifying lists: inserting, appending, and removing elements.
- Accessing and assigning values using indices.
- **Common Question Types:**
- Tracing code that manipulates lists.
- Writing code to perform specific operations on lists (e.g., search, filter, modify).
- Analyzing the efficiency of list algorithms (e.g., linear search).
- **Last-Minute Tips:**
- **Pay attention to indexing:** Remember that AP Pseudocode starts at 1, while Python starts at 0. - **Practice tracing:** Work through code examples step-by-step to understand how lists are modified.
- **Don't panic:** If you get stuck, try to break the problem down into smaller parts.

## 
<div data-custom-tag="practice_question"> 

Practice Questions

</div>

### Multiple Choice Questions

1. What is the output of the following code?
  ```
python
  my_list = [10, 20, 30, 40]
  my_list.insert(2, 25)
  print(my_list[3])
  ```
  (A) 20 (B) 25 (C) 30 (D) 40

2. What will `my_list` be after executing the following code?
  ```
python
  my_list = ["a", "b", "c", "d"]
  my_list[1] = my_list[3]
  my_list.remove("d")
  ```
  (A) `["a", "b", "c"]` (B) `["a", "d", "c"]` (C) `["a", "d", "c", "d"]` (D) `["a", "b", "c", "d"]`

3. What is the output of the following code?
  ```
python
  my_list = [5, 10, 15, 20]
  print(len(my_list))
  ```
  (A) 3 (B) 4 (C) 5 (D) Error

### Free Response Question

**Question:**

A list of integers, `numbers`, is given. Write a code segment that calculates the sum of all even numbers in the list and stores the result in the variable `even_sum`. Assume the list `numbers` is already initialized.

**Scoring Breakdown:**

*   **Initialization (1 point):** Correctly initialize `even_sum` to 0. *   **Looping (2 points):** Correctly iterate through all elements of the list.
*   **Conditional Check (2 points):** Correctly identify even numbers.
*   **Summation (1 point):** Correctly add even numbers to `even_sum`.

**Example Solution:**

python even_sum = 0 for num in numbers: if num % 2 == 0: even_sum += num


Remember, you've got this! Go in there, stay calm, and show them what you know. You're ready! 💪