CP125
Topic 2: Lists
Learning Outcomes:
(a) Identify concepts of lists
Table of Contents
CP125
Characteristics of a List
✅ Ordered – Elements are stored in a specific sequence.�✅ Mutable – Can be modified (add, remove, update elements).�✅ Allows Duplicates – Can have repeated values.�✅ Supports Different Data Types – Can store integers, strings, floats, or even other lists.�✅ Dynamic Size – Can grow or shrink as needed.
CP125
Characteristic 1 | Description |
Ordered |
|
Code |
fruits = ["Apple", "Banana", "Cherry"] print(fruits[0]) # Output: Apple (order is maintained) |
CP125
Code |
days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"] print(days[0]) # Output: Monday print(days[4]) # Output: Friday |
Code |
scores = [90, 85, 88, 92, 80] print(scores) # Output: [90, 85, 88, 92, 80] |
CP125
Characteristic 2 | Description |
Changeable/ Mutable |
|
Code |
numbers = [10, 20, 30] numbers[1] = 25 # Modifying the second element print(numbers) # Output: [10, 25, 30] |
CP125
Code |
names = ["Ali", "Sara", "John"] names[1] = "Aisha" # Changing "Sara" to "Aisha" print(names) # Output: ['Ali', 'Aisha', 'John'] |
Code |
fruits = ["Apple", "Banana", "Cherry"] fruits.append("Orange") # Adding an element fruits.remove("Banana") # Removing an element print(fruits) # Output: ['Apple', 'Cherry', 'Orange'] |
CP125
Characteristic 3 | Description |
Allow Duplicate |
|
Code |
names = ["Ali", "Sara", "Ali", "John"] print(names) # Output: ['Ali', 'Sara', 'Ali', 'John'] |
CP125
Code |
prices = [15.99, 25.50, 15.99, 30.00, 25.50, 45.75] print(prices) # Output: [15.99, 25.50, 15.99, 30.00, 25.50, 45.75] |
Code |
temperatures = [30.5, 32.0, 31.5, 30.5, 32.0, 31.5] print(temperatures) # Output: [30.5, 32.0, 31.5, 30.5, 32.0, 31.5] |
CP125
Characteristic 4 | Description |
Supports Different Data Types | A list can store multiple data types in a single structure. |
Code |
mixed_list = [5, "Hello", 3.5, True] print(mixed_list) # Output: [5, 'Hello', 3.5, True] |
CP125
Code |
info = ["Ali", 18, 3.5, True] print(info) # Output: ['Ali', 18, 3.5, True] |
Code |
nested_list = [[1, 2, 3], ["A", "B", "C"], [True, False]] print(nested_list[1]) # Output: ['A', 'B', 'C'] |
CP125
Characteristic 5 | Description |
Dynamic Size | Lists can grow or shrink by adding or removing elements. |
Code |
numbers = [1, 2, 3, 4, 5] numbers.append(6) # Adding an element numbers.remove(3) # Removing element 3 print(numbers) # Output: [1, 2, 4, 5, 6] |
CP125
Code |
colors = ["Red", "Blue"] colors.append("Green") # Adding another color print(colors) # Output: ['Red', 'Blue', 'Green'] |
Code |
colors = ["Red", "Blue"] colors.remove("Red") #Remove another color print(colors) # Output: ['Blue'] |
CP125
Exercise
2. What is the index number for "mobile" in the list ["pc", "laptop", "mobile", "computer" ,[1, 4, 3]]?
3. What is the index number for [1, 4, 3] in the list ["pc", "laptop", "mobile", "computer" ,[1, 4, 3]]?
CP125