Computer ScienceChapter 3: Programming Fundamentals
3.2.1 List
List
Explanation level
Introduction
A list is a basic data structure in Python that holds groups of elements in a sequential manner. This flexibility allows a list to store elements of various data types such as boolean, integers, etc. The order in which things are added is maintained by lists — index 0 will have the first item inserted, index 1 will have the second, and so on. This arrangement is essential for retrieving elements based on their location.
The textbook explains that different data types can be stored as elements in the same list. List sizes are dynamic, meaning elements can be added or removed as required.
Definition
List is a basic data structure in Python that stores an ordered collection of items which can be accessed by their index. Lists are mutable, meaning their contents can be changed.
In simple words: A list is like a container that holds multiple items in a specific order, and you can change, add, or remove items whenever you want.
Main Idea
- Store multiple items in a single variable.
- Access items by their position (index).
- Add, remove, or change items.
- Store items of different data types in the same list.
- Grow and shrink in size as needed.
The textbook uses a list of student grades to demonstrate common list operations.
Core Concept
Creating a List A list is created by placing elements inside square brackets `[]`, separated by commas.
Example from the book (line 1): ```python student_grades = [85, 92, 78, 95, 82] ``` This creates a list named `student_grades` with 5 elements.
Common List Operations
The textbook demonstrates the following operations:
1. Inserting an Element at a Specific Position The `insert()` function adds an element at a specified index.
Example from the book (line 3): ```python student_grades.insert(2, 90) ``` This inserts the value `90` at index `2`. The list becomes: ```python [85, 92, 90, 78, 95, 82] ``` Output from the book: "Grades after adding a new grade: [85, 92, 90, 78, 95, 82]"
2. Appending an Element at the End The `append()` function adds an element at the end of the list.
Example from the book (line 5): ```python student_grades.append(100) ``` This adds `100` at the end. The list becomes: ```python [85, 92, 90, 78, 95, 82, 100] ``` Output from the book: "Grades after adding another new grade: [85, 92, 90, 78, 95, 82, 100]"
3. Removing an Element by Value The `remove()` function removes the first occurrence of a specified value.
Example from the book (line 8): ```python student_grades.remove(78) ``` This removes the value `78`. The list becomes: ```python [85, 92, 90, 95, 82, 100] ``` Output from the book: "Grades after removing a grade: [85, 92, 90, 95, 82, 100]"
4. Removing an Element by Index The `pop()` function removes and returns the element at a specified index.
Example from the book (line 10): ```python lowest_grade = student_grades.pop(2) ``` This removes the element at index `2` (which is `90`). The list becomes: ```python [85, 92, 95, 82, 100] ``` Output from the book: "Grades after removing the grade on index 2: [85, 92, 95, 82, 100]"
5. Checking if an Element Exists The `in` operator checks whether a value exists in the list.
Example from the book (lines 13–16): ```python if 88 in student_grades: student_grades.remove(88) else: print("Grade 88 not found in the list") ``` Since `88` is not in the list, the output is: "Grade 88 not found in the list"
Why this matters: A good programming practice is to use conditional (if-else) statements before removing a value. This way, if the number is not in the list, it won't abnormally terminate the program; instead, a message is printed.
6. Calculating the Average The `sum()` and `len()` functions can be used together to calculate the average without using a loop.
Example from the book (lines 18–19): ```python average_grade = sum(student_grades) / len(student_grades) print("Average grade:", average_grade) ``` Output from the book: "Average grade: 90.8"
- Ordered: Items are stored in a specific order and can be accessed by index.
- Mutable: Items can be changed, added, or removed after the list is created.
- Dynamic: The size of the list can grow or shrink as needed.
- Heterogeneous: A single list can store items of different data types (e.g., integers, strings, booleans).
Activity 1 (from the book) The textbook provides an activity: "Extend the program of Fig. 3.2 to search for all odd numbers in the list and remove them."
This activity encourages the student to apply the list operations they have learned to a new problem.
Intermediate Level
Lists are versatile because they support many operations. The textbook demonstrates:
| Operation | Function | Example |
|---|---|---|
| Insert at position | `insert(index, value)` | `student_grades.insert(2, 90)` |
| Add at end | `append(value)` | `student_grades.append(100)` |
| Remove by value | `remove(value)` | `student_grades.remove(78)` |
| Remove by index | `pop(index)` | `student_grades.pop(2)` |
| Check existence | `in` operator | `if 88 in student_grades:` |
| Calculate sum | `sum(list)` | `sum(student_grades)` |
| Count elements | `len(list)` | `len(student_grades)` |
The textbook also notes that using conditional statements before removing a value is good practice. This prevents the program from crashing if the value is not found.
Important Points
- - List: A basic data structure in Python that stores an ordered collection of items.
- - Lists are mutable: Their contents can be changed after creation.
- - Lists are dynamic: They can grow and shrink as needed.
- - Lists can store different data types: Integers, strings, booleans, etc., can be mixed in the same list.
- - Common operations:
- - `insert(index, value)`: Insert at a specific position.
- - `append(value)`: Add at the end.
- - `remove(value)`: Remove the first occurrence of a value.
- - `pop(index)`: Remove the element at a specific index.
- - `in` operator: Check if a value exists.
- - `sum()` and `len()`: Calculate sum and count elements.
- - Good practice: Use conditional statements before removing a value to avoid errors.
Remember
- - List = Ordered, mutable collection of items.
- - Index starts at 0.
- - **0** = Insert at position.
- - **0** = Add at end.
- - **0** = Remove by value.
- - **0** = Remove by index.
- - `in` operator = Check if value exists.
- - `sum()` and `len()` = Calculate average without a loop.
- - Use `if` before `remove()` to avoid errors.
Common Mistakes
- 1. Forgetting that index starts at 0 — The first element is at index 0, not 1.
- 2. Using `remove()` with an index — `remove()` takes a value, not an index. Use `pop()` for index-based removal.
- 3. Using `pop()` with a value — `pop()` takes an index, not a value. Use `remove()` for value-based removal.
- 4. Not checking if a value exists before removing — This can cause a `ValueError` if the value is not in the list.
- 5. Confusing lists with tuples — Lists are mutable (can be changed); tuples are immutable (cannot be changed).
- 6. Thinking `append()` and `insert()` are the same — `append()` adds at the end; `insert()` adds at a specific position.
Quick Revision
- List: A basic data structure in Python that holds groups of elements in a sequential manner. Lists are ordered, mutable, dynamic, and can store different data types.
- Creating a list: Use square brackets `[]` with comma-separated values.
- Common operations:
- `insert(index, value)`: Inserts an element at a specified index.
- `append(value)`: Adds an element at the end.
- `remove(value)`: Removes the first occurrence of a value.
- `pop(index)`: Removes and returns the element at a specified index.
- `in` operator: Checks if a value exists in the list.
- `sum(list)` and `len(list)`: Calculate sum and count elements.
- Good practice: Use conditional statements before removing a value to avoid errors.
- Activity 1: Extend the program to search for all odd numbers in the list and remove them.
60-Second Revision
- List = Ordered, mutable collection.
- Index starts at 0.
- **0** = Insert at position.
- **0** = Add at end.
- **0** = Remove by value.
- **0** = Remove by index.
- `in` operator = Check existence.
- **0 + 1** = Average.
- Warning: Use `if` before `remove()` to avoid errors.
Frequently Asked Questions (FAQs)
Q1. What is a list in Python? Answer: A list is a basic data structure in Python that holds groups of elements in a sequential manner. It is an ordered, mutable collection of items that can be accessed by their index. Lists can store elements of various data types and can grow or shrink in size as needed.
- Ordered: Items are stored in a specific order and can be accessed by index.
- Mutable: Items can be changed, added, or removed after the list is created.
- Dynamic: The size of the list can grow or shrink as needed.
- Heterogeneous: A single list can store items of different data types.
- Q3. How do you insert an element at a specific position in a list?
- Answer: Use the `insert(index, value)` function. For example, `student_grades.insert(2, 90)` inserts the value `90` at index `2`.
- Q4. How do you add an element at the end of a list?
- Answer: Use the `append(value)` function. For example, `student_grades.append(100)` adds `100` at the end of the list.
- Q5. How do you remove an element by its value?
- Answer: Use the `remove(value)` function. For example, `student_grades.remove(78)` removes the first occurrence of `78` from the list.
- Q6. How do you remove an element by its index?
- Answer: Use the `pop(index)` function. For example, `student_grades.pop(2)` removes and returns the element at index `2`.
- Q7. How do you check if a value exists in a list?
- Answer: Use the `in` operator. For example, `if 88 in student_grades:` checks if `88` is in the list.
Q8. How do you calculate the average of a list of numbers? Answer: Use the `sum()` and `len()` functions together. For example, `average_grade = sum(student_grades) / len(student_grades)` calculates the average without using a loop.
Q9. Why is it good practice to use a conditional statement before removing a value from a list? Answer: It is good practice because if the value is not in the list, `remove()` will raise a `ValueError` and abnormally terminate the program. Using an `if` statement checks if the value exists before attempting to remove it, preventing the error.
- Q10. What is the difference between `append()` and `insert()`?
- Answer: `append(value)` adds an element at the end of the list. `insert(index, value)` adds an element at a specific position (index) in the list.
Q11. What is Activity 1 in the textbook? Answer: Activity 1 asks students to extend the program of Fig. 3.2 to search for all odd numbers in the list and remove them. This activity encourages applying the list operations learned in the section to a new problem.
Practice Questions
Short Response Questions (SRQs)
- Define a list in Python and explain its characteristics.
- How do you create a list in Python? Give an example.
- Explain the difference between `append()` and `insert()`.
- How do you remove an element from a list by value and by index?
- How do you calculate the average of a list of numbers without using a loop?
Extended Response Questions (ERQs)
- Discuss the characteristics of a Python list. Why is it considered a flexible data structure?
- Explain the common list operations (insert, append, remove, pop, in operator, sum, len) with examples.
- Analyze the importance of using conditional statements before removing a value from a list. Provide an example of what can go wrong without them.
- You are writing a Python program to manage student grades. Describe how you would use lists and list operations to add, remove, and calculate the average of grades.
- Compare and contrast lists and tuples in Python. Why would you choose one over the other?
- Extend the program from the textbook to search for all odd numbers in the list and remove them. Write the complete code and explain the steps.
Multiple Choice Questions (MCQs)
- Q1. What is a list in Python?
- A. An immutable collection of items
- B. An ordered, mutable collection of items
- C. A type of function
- D. A type of loop
- Correct Answer: B
- Explanation: A list is an ordered, mutable collection of items.
- Q2. Which function is used to add an element at the end of a list?
- A. `insert()`
- B. `append()`
- C. `remove()`
- D. `pop()`
- Correct Answer: B
- Explanation: The `append()` function adds an element at the end of a list.
- Q3. Which function is used to insert an element at a specific position in a list?
- A. `append()`
- B. `insert()`
- C. `remove()`
- D. `pop()`
- Correct Answer: B
- Explanation: The `insert(index, value)` function inserts an element at a specific position.
- Q4. Which function is used to remove an element by its value?
- A. `pop()`
- B. `append()`
- C. `remove()`
- D. `insert()`
- Correct Answer: C
- Explanation: The `remove(value)` function removes the first occurrence of a value.
- Q5. Which function is used to remove an element by its index?
- A. `remove()`
- B. `pop()`
- C. `append()`
- D. `insert()`
- Correct Answer: B
- Explanation: The `pop(index)` function removes and returns the element at a specific index.
- Q6. How do you check if a value exists in a list?
- A. Using the `in` operator
- B. Using the `exists()` function
- C. Using the `find()` function
- D. Using the `check()` function
- Correct Answer: A
- Explanation: The `in` operator checks if a value exists in a list.
- Q7. How do you calculate the average of a list of numbers?
- A. Using `sum()` and `len()`
- B. Using `average()` function
- C. Using `mean()` function
- D. Using `avg()` function
- Correct Answer: A
- Explanation: The average is calculated using `sum(list) / len(list)`.
- Q8. What happens if you try to remove a value that is not in the list?
- A. Nothing happens
- B. A `ValueError` is raised
- C. The list is cleared
- D. The program crashes silently
- Correct Answer: B
- Explanation: Trying to remove a value that is not in the list raises a `ValueError`.
- Q9. What is the index of the first element in a Python list?
- A. 1
- B. 0
- C. -1
- D. Depends on the list
- Correct Answer: B
- Explanation: In Python, indexing starts at 0, so the first element is at index 0.
- Q10. Which of the following is true about Python lists?
- A. They can only store integers
- B. They have a fixed size
- C. They can store different data types
- D. They cannot be changed after creation
- Correct Answer: C
- Explanation: Python lists can store different data types and are mutable and dynamic.
- Q11. What is Activity 1 in the textbook?
- A. Calculate the average of a list
- B. Search for all odd numbers in the list and remove them
- C. Insert a new element at the beginning
- D. Sort the list in descending order
- Correct Answer: B
- Explanation: Activity 1 asks students to search for all odd numbers in the list and remove them.
- Q12. Which function returns the number of elements in a list?
- A. `count()`
- B. `len()`
- C. `size()`
- D. `length()`
- Correct Answer: B
- Explanation: The `len()` function returns the number of elements in a list.
Did you understand this topic?
Your answer is saved with your learning record. It does not mark the topic as mastered.
Quick revision
Revision Zone
Review the key facts, formulas and checks before you move on.3.2.1 List
Sticky Notes · Quick Revision
Key Point 1
- List = Ordered, mutable collection.
Key Point 2
- Index starts at 0.
Key Point 3
- **0** = Insert at position.
Key Point 4
- **0** = Add at end.
Key Point 5
- **0** = Remove by value.
Key Point 6
- **0** = Remove by index.
Key Point 7
- `in` operator = Check existence.
Key Point 8
- **0 + 1** = Average.
Key Point 9
- Use `if` before `remove()`.
Same supplied content as this Notes page (shared canonical source).