Computer ScienceChapter 3: Programming Fundamentals (Python)
3.10 List
A **list** in Python is a collection of items stored in a single variable, where each item has a specific position called an index
Explanation level
Introduction
In programming, we often need to store multiple values together. For example, a list of student names, a list of marks, or a list of daily temperatures. Python provides a data structure called list to handle these situations. A list can hold multiple items in a single variable.
Definition
A list in Python is a collection of items stored in a single variable, where each item has a specific position called an index.
In simple words, a list is like a container that can hold multiple values in a specific order.
Main Idea
Lists are used to manoeuvre a series of similar values. They are represented by square brackets `[_,_]`. A list can hold values of any data type — numbers, strings, or even other lists. Lists are mutable, meaning their contents can be changed after they are created.
Core Concept
- A list is an ordered collection — items have a specific position (index).
- A list is mutable — items can be added, removed, or changed.
- A list can hold duplicate values.
- A list can hold different data types in the same list.
- Indexing starts at 0 — the first item is at index 0.
Detailed Explanation
Creating a List
Lists are created by placing items inside square brackets `[]`, separated by commas.
Example — Creating Lists: ```python # List of odd single-digit numbers SngLDgtOddNums = [1, 3, 5, 7, 9]
List of names names = ["Ali", "Sara", "Ahmed"]
List of mixed data types mixed = [1, "Hello", 3.14, True]
Empty list empty = [] ```
Accessing List Elements
Each item in a list has an index. The first item is at index 0, the second at index 1, and so on.
Example — Accessing Elements: ```python SngL_Dgt_Odd_Nums = [1, 3, 5, 7, 9] print(SngL_Dgt_Odd_Nums[0]) # 1 print(SngL_Dgt_Odd_Nums[1]) # 3 print(SngL_Dgt_Odd_Nums[4]) # 9 ```
Basic List Operations
Example — Iterating Through a List: ```python SngL_Dgt_Odd_Nums = [1, 3, 5, 7, 9] for i in range(len(SngL_Dgt_Odd_Nums)): print('List element number', i+1, ':', SngL_Dgt_Odd_Nums[i]) ```
Output: ``` List element number 1 : 1 List element number 2 : 3 List element number 3 : 5 List element number 4 : 7 List element number 5 : 9 ```
- `len(SngL_Dgt_Odd_Nums)` returns the number of elements in the list (5)
- `range(len(...))` generates indices 0 to 4
- `SngL_Dgt_Odd_Nums[i]` accesses each element by index
Built-in List Functions
Python provides several built-in functions for working with lists.
Example — Sum, Min, Max: ```python SngL_Dgt_Odd_Nums = [1, 3, 5, 7, 9] print('Sum of all elements of List:', sum(SngL_Dgt_Odd_Nums)) print('Smallest number in the List:', min(SngL_Dgt_Odd_Nums)) print('Largest number in the List:', max(SngL_Dgt_Odd_Nums)) ```
Output: ``` Sum of all elements of List: 25 Smallest number in the List: 1 Largest number in the List: 9 ```
Summary Table:
| Function | Purpose | Example | Result |
|---|---|---|---|
| `len(list)` | Number of elements | `len([1, 3, 5])` | `3` |
| `sum(list)` | Sum of all elements | `sum([1, 3, 5])` | `9` |
| `min(list)` | Smallest element | `min([1, 3, 5])` | `1` |
| `max(list)` | Largest element | `max([1, 3, 5])` | `5` |
The insert() Function
Another useful function is `insert()`, which inserts an element in the list at a specified position.
Syntax: ```python list_name.insert(index, element) ```
Example: ```python SngL_Dgt_Odd_Nums = [1, 3, 5, 7, 9] SngL_Dgt_Odd_Nums.insert(2, 5) print('List:', SngL_Dgt_Odd_Nums) print('First 5 is found on index:', SngL_Dgt_Odd_Nums.index(5)) ```
Output: ``` List: [1, 3, 5, 5, 7, 9] First 5 is found on index: 2 ```
- `insert(2, 5)` inserts `5` at index `2`
- The list now has duplicate values of `5` (at index 2 and index 3)
- `index(5)` returns the position of the first occurrence of `5`
The index() Function
The `index()` function returns the position of a number in the list.
Important: In case of multiple occurrences of the said number, the placement of the first match is returned.
Example: ```python nums = [10, 20, 30, 20, 40] print(nums.index(20)) # 1 (first occurrence) ```
Duplicate Values in a List
A list can have duplicate values. If we insert another value of 5, other than the one at index number 2, let's say at the end of the list, the list will now hold more than one value of 5, i.e. on index numbers 2 and 5.
Example: ```python nums = [1, 3, 5, 7, 9] nums.append(5) print(nums) # [1, 3, 5, 7, 9, 5] print(nums.index(5)) # 2 (first occurrence) ```
Adding Random Numbers to a List
Next, let's introduce some dynamicity in our code by introducing random numbers. Among the modules that Python provides for convenience is the `random` module which consists of many inbuilt functions like `randint()` and can be used by importing in the code, with the `import` keyword.
Once defined at the start of the program, the function can be used anywhere in the program to generate a random number, in the given range.
Example — Generate 10 Random Numbers: ```python from random import randint
Rnums = [] for i in range(10): Rnums.append(randint(1, 99)) print(Rnums) ```
Output (example): ``` [66, 1, 6, 15, 83, 8, 73, 15, 30, 7] ```
- `from random import randint` — imports the `randint` function
- `Rnums = []` — creates an empty list
- `Rnums.append(randint(1, 99))` — generates a random number between 1 and 99 and adds it to the list
- The loop runs 10 times, so 10 random numbers are added
Note: The output will be different each time you run the program because the numbers are random.
Searching for a Number in a List
Let us extend the same code, where we initially populate random numbers and later try to find a particular number in the list. The two possible outcomes are either the number is in the list or not.
Example — Search for 7 in a List: ```python from random import randint
numseek = 7 temp = 0 Rnums = []
for i in range(10): Rnums.append(randint(1, 99)) print(Rnums)
for i in range(len(Rnums)): if numseek == Rnums[i]: temp = temp + 1
if temp > 0: print("7 is on index: ", Rnums.index(7)) else: print('7 is not in the list') ```
Output (Run 1): ``` [27, 20, 34, 56, 36, 48, 47, 13, 9, 12] 7 is not in the list ```
Output (Run 2): ``` [7, 81, 77, 83, 41, 67, 58, 75, 65, 97] 7 is on Index: 0 ```
- `numseek = 7` — the number we are searching for
- `temp = 0` — a counter to track if the number is found
- The first loop populates the list with random numbers
- The second loop checks each element to see if it matches `numseek`
- If found, `temp` is incremented
- After the loop, if `temp > 0`, the number was found
- The `index()` function returns the position of the first occurrence
Membership Operators in Lists
As discussed earlier, the membership operators can be used for checking whether a particular element exists in an object, like a list.
Example: ```python L = [1, 3, 5, 7] print(5 in L) # should return True # because value 5 is in the list ```
Output: ``` True ```
The membership operators are quite useful to control the flow of the program dynamically by incorporating respective logic based on the values.
Example — Search Using `in`: ```python from random import randint
Rnums = [] for i in range(10): Rnums.append(randint(1, 99)) print(Rnums)
if 7 in Rnums: print("7 is on index: ", Rnums.index(7)) else: print("7 is not in the list") ```
This is simpler than manually looping through the list.
The append() Function
The `append()` function adds an element to the end of the list.
Example: ```python nums = [1, 2, 3] nums.append(4) print(nums) # [1, 2, 3, 4] ```
The remove() Function
The `remove()` function removes the first occurrence of a specified value.
Example: ```python nums = [1, 2, 3, 2, 4] nums.remove(2) print(nums) # [1, 3, 2, 4] ```
The pop() Function
The `pop()` function removes and returns an element at a specified index (or the last element if no index is given).
Example: ```python nums = [1, 2, 3, 4, 5] nums.pop() # Removes and returns 5 nums.pop(0) # Removes and returns 1 print(nums) # [2, 3, 4] ```
Intermediate Level
Common List Methods
| Method | Purpose | Example | Result |
|---|---|---|---|
| `append(x)` | Add x to end | `[1,2].append(3)` | `[1,2,3]` |
| `insert(i, x)` | Insert x at index i | `[1,3].insert(1,2)` | `[1,2,3]` |
| `remove(x)` | Remove first x | `[1,2,2].remove(2)` | `[1,2]` |
| `pop()` | Remove and return last | `[1,2,3].pop()` | returns 3 |
| `pop(i)` | Remove and return index i | `[1,2,3].pop(0)` | returns 1 |
| `index(x)` | Find first index of x | `[1,2,3].index(2)` | `1` |
| `count(x)` | Count occurrences of x | `[1,2,2].count(2)` | `2` |
| `sort()` | Sort the list | `[3,1,2].sort()` | `[1,2,3]` |
| `reverse()` | Reverse the list | `[1,2,3].reverse()` | `[3,2,1]` |
| `clear()` | Remove all elements | `[1,2,3].clear()` | `[]` |
| `copy()` | Make a copy | `[1,2,3].copy()` | new list |
| `extend(x)` | Add all items from x | `[1,2].extend([3,4])` | `[1,2,3,4]` |
Built-in Functions for Lists
| Function | Purpose | Example | Result |
|---|---|---|---|
| `len()` | Number of elements | `len([1,2,3])` | `3` |
| `sum()` | Sum of elements | `sum([1,2,3])` | `6` |
| `min()` | Smallest element | `min([1,2,3])` | `1` |
| `max()` | Largest element | `max([1,2,3])` | `3` |
| `sorted()` | Return sorted copy | `sorted([3,1,2])` | `[1,2,3]` |
Slicing Lists
You can extract a portion of a list using slicing.
Syntax: ```python list_name[start:end] ```
Example: ```python nums = [10, 20, 30, 40, 50] print(nums[1:4]) # [20, 30, 40] print(nums[:3]) # [10, 20, 30] print(nums[2:]) # [30, 40, 50] print(nums[:]) # [10, 20, 30, 40, 50] ```
Important: The `end` index is not inclusive.
Modifying List Elements
Since lists are mutable, you can change individual elements.
Example: ```python nums = [1, 2, 3] nums[0] = 100 print(nums) # [100, 2, 3] ```
Lists vs Tuples
| Feature | List | Tuple |
|---|---|---|
| Brackets | `[1, 2, 3]` | `(1, 2, 3)` |
| Mutable | Yes | No |
| Can add/remove | Yes | No |
| Speed | Slower | Faster |
| Use case | When data may change | When data is fixed |
Formula / Mathematical Form
Not applicable for this topic.
Solved Example
Example — Find the Largest and Smallest Numbers in a List
Given: - A list of numbers: `[45, 12, 78, 34, 89, 23]`
Required: - Find the largest and smallest numbers
Code: ```python nums = [45, 12, 78, 34, 89, 23] print("List:", nums) print("Largest number:", max(nums)) print("Smallest number:", min(nums)) ```
Output: ``` List: [45, 12, 78, 34, 89, 23] Largest number: 89 Smallest number: 12 ```
- `max(nums)` returns the largest element in the list (89)
- `min(nums)` returns the smallest element in the list (12)
Example — Sum and Average of a List
Code: ```python nums = [10, 20, 30, 40, 50] total = sum(nums) average = total / len(nums) print("Sum:", total) print("Average:", average) ```
Output: ``` Sum: 150 Average: 30.0 ```
Important Points
- - A list is a collection of items stored in a single variable.
- - Lists are created using square brackets `[]`.
- - Each item in a list has an index, starting from 0.
- - Lists are mutable — items can be added, removed, or changed.
- - Lists can hold duplicate values.
- - Lists can hold different data types in the same list.
- - `len(list)` returns the number of elements.
- - `sum(list)` returns the sum of all elements.
- - `min(list)` returns the smallest element.
- - `max(list)` returns the largest element.
- - `insert(index, element)` inserts an element at a specified position.
- - `index(value)` returns the position of the first occurrence of a value.
- - `append(x)` adds x to the end of the list.
- - `remove(x)` removes the first occurrence of x.
- - `pop()` removes and returns the last element.
- - Membership operators (`in`, `not in`) check if a value exists in a list.
- - Random numbers can be generated using the `random` module's `randint()` function.
Remember
- - List = Collection of items in a single variable.
- - Square brackets `[]` = Create a list.
- - Index starts at 0.
- - Lists are mutable — can be changed.
- - **0** = Number of elements.
- - **0, 1, 2** = Built-in functions.
- - **0** = Add to end.
- - **0** = Insert x at index i.
- - **0** = Remove first x.
- - **0** = Position of first x.
- - **0** = Check membership.
- - `randint(a, b)` = Random number between a and b.
Common Mistakes
- - Forgetting index starts at 0: `list[0]` is the first element, not `list[1]`.
- - Confusing append and insert: `append()` adds to end; `insert()` adds at a specific position.
- - Thinking lists are immutable: Lists are mutable — you can change them.
- - Confusing list with tuple: Lists use `[]`; tuples use `()`.
- - Forgetting to import random: `import random` or `from random import randint` needed.
- - Using index() on a value not in the list: Causes a `ValueError`.
- - Thinking index() returns all positions: It returns only the first occurrence.
- - Modifying a list while iterating: Can cause unexpected behavior.
Quick Revision
A list in Python is a collection of items stored in a single variable. It is represented by square brackets `[_,_]`. A list can hold values of any data type. Lists are mutable — their contents can be changed after creation.
Lists are used to manoeuvre a series of similar values. A list has an index starting from 0. Each item in a list can be accessed by its index.
- `len()` — number of elements
- `sum()` — sum of all elements
- `min()` — smallest element
- `max()` — largest element
- `insert(index, element)` — insert at position
- `append(element)` — add to end
- `remove(element)` — remove first occurrence
- `index(element)` — find position of first occurrence
The `random` module's `randint()` function can be used to generate random numbers and add them to a list.
Membership operators (`in`, `not in`) check if a value exists in a list.
60-Second Revision
- List = Collection in a single variable.
- **0** = Create list.
- Index starts at 0.
- Mutable — can be changed.
- `len()`, `sum()`, `min()`, `max()` — built-in functions.
- **0** = add to end; **1** = insert at i.
- `remove(x)` = remove first x; `index(x)` = position of first x.
- **0** = check membership.
- `randint(a, b)` = random number between a and b.
- Warning: Index starts at 0. Forgetting this causes wrong element access.
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.10 List
Sticky Notes · Quick Revision
Key Point 1
- List = Collection in a single variable.
Key Point 2
- **0** = Create list.
Key Point 3
- Index starts at 0.
Key Point 4
- Mutable — can be changed.
Key Point 5
- `len()`, `sum()`, `min()`, `max()` — built-in functions.
Key Point 6
- **0** = add to end.
Key Point 7
- **0** = insert at i.
Key Point 8
- **0** = remove first x.
Key Point 9
- **0** = position of first x.
Key Point 10
- **0** = check membership.
Key Point 11
- **0** = random number.
Same supplied content as this Notes page (shared canonical source).