Chapter 09: Lists
9.1 Introduction to List
- A list is an ordered, mutable sequence that can contain elements of different data types.
- Lists are defined using square brackets
[]with elements separated by commas. - They support indexing (starting from 0) and slicing like strings.
- Lists can be nested (a list inside another list).
9.1.1 Accessing List Elements
Code: Creating and Accessing Lists
# Creating different types of lists
list1 = [2, 4, 6, 8, 10] # List of integers
list2 = ['apple', 'banana', 'cherry'] # List of strings
list3 = [1, 'hello', 3.14, True] # Mixed data types
list4 = [[1, 2, 3], ['a', 'b', 'c']] # Nested list
# Accessing elements
print(list1[0]) # Output: 2
print(list2[-1]) # Output: cherry
print(list4[1][0]) # Output: a
Code: Nested List Access
student_data = [
['Alice', 85, 'Math'],
['Bob', 92, 'Science'],
['Charlie', 78, 'English']
]
# Accessing nested list elements
print(student_data[0][0]) # Output: Alice
print(student_data[1][2]) # Output: Science
9.1.2 Lists are Mutable
- Lists can be modified after creation (unlike strings).
- Elements can be reassigned using indexing.
Code: Modifying Lists
colors = ['red', 'green', 'blue']
colors[1] = 'yellow' # Modify second element
print(colors) # Output: ['red', 'yellow', 'blue']
colors.append('purple') # Add new element
print(colors) # Output: ['red', 'yellow', 'blue', 'purple']
9.2 List Operations
9.2.1 Concatenation
Use
+to join lists.list1 = [1, 2, 3] list2 = [4, 5, 6] result = list1 + list2 print(result) # Output: [1, 2, 3, 4, 5, 6]
9.2.2 Repetition
Use
*to repeat lists.list1 = [7, 8] result = list1 * 3 print(result) # Output: [7, 8, 7, 8, 7, 8]
9.2.3 Membership
Use
inandnot into check for elements.list1 = ['a', 'b', 'c'] print('b' in list1) # Output: True print('z' not in list1) # Output: True
*Code: Membership & Repetition
# Membership
fruits = ['apple', 'mango', 'banana']
if 'apple' in fruits:
print("Apple is in the list")
# Repetition
pattern = ['x', 'o'] * 4
print(pattern) # Output: ['x', 'o', 'x', 'o', 'x', 'o', 'x', 'o']
9.2.4 Slicing
- Works similar to strings:
list[start:stop:step].
Code: List Slicing
numbers = [10, 20, 30, 40, 50, 60, 70]
print(numbers[2:5]) # Output: [30, 40, 50]
print(numbers[:3]) # Output: [10, 20, 30]
print(numbers[::2]) # Output: [10, 30, 50, 70]
print(numbers[::-1]) # Output: [70, 60, 50, 40, 30, 20, 10]
9.3 Traversing a List
Using for loop:
list1 = ['red', 'green', 'blue']
for color in list1:
print(color)
Using while loop:
list1 = ['red', 'green', 'blue']
i = 0
while i < len(list1):
print(list1[i])
i += 1
Code: Traversing with Index
fruits = ['apple', 'banana', 'cherry']
for i in range(len(fruits)):
print(f"Index {i}: {fruits[i]}")
9.4 List Methods & Built-in Functions
| Method | Description |
||-|
| append(x) | Adds x to the end |
| extend(L) | Adds all elements of list L |
| insert(i, x) | Inserts x at index i |
| remove(x) | Removes first occurrence of x |
| pop(i) | Removes and returns element at i |
| sort() | Sorts the list in-place |
| reverse() | Reverses the list in-place |
| index(x) | Returns index of first x |
| count(x) | Counts occurrences of x |
Code: Using List Methods
# append and extend
nums = [1, 2, 3]
nums.append(4) # nums becomes [1, 2, 3, 4]
nums.extend([5, 6]) # nums becomes [1, 2, 3, 4, 5, 6]
# insert and remove
nums.insert(2, 99) # [1, 2, 99, 3, 4, 5, 6]
nums.remove(99) # [1, 2, 3, 4, 5, 6]
# pop
popped = nums.pop(1) # popped = 2, nums = [1, 3, 4, 5, 6]
9.5 Nested Lists
- A list can contain other lists as elements.
Code: Working with Nested Lists
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Accessing elements
print(matrix[0][1]) # Output: 2
# Traversing nested list
for row in matrix:
for element in row:
print(element, end=' ')
print()
# Output:
# 1 2 3
# 4 5 6
# 7 8 9
9.6 Copying Lists
Shallow copy:
list2 = list1(both refer to same object).Deep copy methods:
- Slicing:
new_list = old_list[:] list():new_list = list(old_list)copy.copy():new_list = copy.copy(old_list)
- Slicing:
Code: Copying Lists
import copy
original = [1, 2, [3, 4]]
shallow = original[:]
deep = copy.deepcopy(original) # For nested structures
original[0] = 99
original[2][0] = 88
print(shallow) # Output: [1, 2, [88, 4]] (nested part changed)
print(deep) # Output: [1, 2, [3, 4]] (fully independent)
9.7 List as Argument to Function
- Lists are passed by reference.
- Modifying the list inside a function affects the original.
- Reassigning the list inside a function creates a new local object.
Code: List as Function Argument
def modify_list(lst):
lst.append(100) # Affects original list
print("Inside function:", lst)
def reassign_list(lst):
lst = [7, 8, 9] # Local copy, original unchanged
print("Inside function:", lst)
my_list = [1, 2, 3]
modify_list(my_list) # my_list becomes [1, 2, 3, 100]
reassign_list(my_list) # my_list remains [1, 2, 3, 100]
9.8 List Manipulation (Program Examples)
Code: List Statistics
def list_stats(numbers):
return {
'sum': sum(numbers),
'average': sum(numbers) / len(numbers),
'max': max(numbers),
'min': min(numbers),
'sorted': sorted(numbers)
}
nums = [45, 12, 78, 23, 56]
stats = list_stats(nums)
for key, value in stats.items():
print(f"{key}: {value}")
Code: Removing Duplicates
def remove_duplicates(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
# Using set (alternative method)
def remove_duplicates_set(lst):
return list(set(lst))
sample = [1, 2, 2, 3, 4, 4, 5]
print(remove_duplicates(sample)) # Output: [1, 2, 3, 4, 5]
Code: List Rotation
def rotate_list(lst, k):
k = k % len(lst) # Handle k larger than list length
return lst[k:] + lst[:k]
original = [1, 2, 3, 4, 5]
print(rotate_list(original, 2)) # Output: [3, 4, 5, 1, 2]
print(rotate_list(original, -1)) # Output: [5, 1, 2, 3, 4]
Key Conceptual Takeaways
- Lists are mutable sequences in Python, i.e., we can change the elements of the list.
- Elements of a list are put in square brackets separated by comma.
- A list within a list is called a nested list. List indexing is same as that of strings and starts at 0. Two way indexing allows traversing the list in the forward as well as in the backward direction.
- Operator + concatenates one list to the end of other list.
- Operator * repeats a list by specified number of times.
- Membership operator in tells if an element is present in the list or not and not in does the opposite.
- Slicing is used to extract a part of the list.
- There are many list manipulation functions including: len(), list(), append(), extend(), insert(), count(), find(), remove(), pop(), reverse(), sort(), sorted(), min(), max(), sum().