Lists in Python
# Lists in Python
Welcome to Chapter 10! Lists are Python's most versatile and commonly used data structure. They can hold any type of data and are mutable — meaning you can add, remove, and modify elements.
---
1. Learning Objectives
- Create and manipulate lists.
- Use indexing, slicing, and iteration.
- Master list methods (append, insert, remove, sort, etc.).
- Write list comprehensions.
- Work with nested lists.
- Build a to-do list app.
---
2. Creating Lists
```python id="py10ex1" # Different ways to create lists numbers = [1, 2, 3, 4, 5] fruits = ["apple", "banana", "cherry"] mixed = [1, "hello", 3.14, True, None] empty = []
# Using list() constructor fromrange = list(range(1, 6)) # [1, 2, 3, 4, 5] fromstring = list("Python") # ['P', 'y', 't', 'h', 'o', 'n']
print(numbers) print(mixed) print(fromstring)
python id="py10_ex2" colors = ["red", "green", "blue", "yellow", "purple"]
# Indexing print(colors[0]) # red print(colors[-1]) # purple
# Slicing print(colors[1:3]) # ['green', 'blue'] print(colors[:3]) # ['red', 'green', 'blue'] print(colors[2:]) # ['blue', 'yellow', 'purple'] print(colors[::-1]) # reversed list
# Modify by index colors[0] = "pink" print(colors) # ['pink', 'green', 'blue', 'yellow', 'purple']
python id="py10ex3" fruits = ["apple", "banana"]
# Adding elements fruits.append("cherry") # Add to end fruits.insert(1, "mango") # Insert at index 1 fruits.extend(["grape", "kiwi"]) # Add multiple
print(fruits) # ['apple', 'mango', 'banana', 'cherry', 'grape', 'kiwi']
# Removing elements fruits.remove("banana") # Remove by value popped = fruits.pop() # Remove & return last popped2 = fruits.pop(1) # Remove at index 1
# Sorting numbers = [3, 1, 4, 1, 5, 9, 2, 6] numbers.sort() # Ascending in-place print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9] numbers.sort(reverse=True) # Descending print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
# sorted() returns new list (doesn't modify original) original = [3, 1, 2] newsorted = sorted(original) print(original) # [3, 1, 2] — unchanged print(new_sorted) # [1, 2, 3]
# Other methods nums = [1, 2, 3, 2, 1] print(nums.count(2)) # 2 print(nums.index(3)) # 2 nums.reverse() print(nums) # [1, 2, 3, 2, 1]
python id="py10_ex4" # Traditional way squares = [] for i in range(1, 6): squares.append(i 2)
# List comprehension (Pythonic!) squares = [i 2 for i in range(1, 6)] print(squares) # [1, 4, 9, 16, 25]
# With condition evens = [x for x in range(20) if x % 2 == 0] print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# With transformation names = ["alice", "bob", "charlie"] capitalized = [name.capitalize() for name in names] print(capitalized) # ['Alice', 'Bob', 'Charlie']
# Nested comprehension matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)] print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
python id="py10_ex5" numbers = [10, 20, 30, 40, 50]
print(len(numbers)) # 5 print(sum(numbers)) # 150 print(min(numbers)) # 10 print(max(numbers)) # 50 print(30 in numbers) # True
# Unpacking first, *rest = numbers print(first) # 10 print(rest) # [20, 30, 40, 50]
# enumerate for idx, val in enumerate(["a", "b", "c"]): print(f"{idx}: {val}")
# zip names = ["Alice", "Bob"] scores = [95, 87] for name, score in zip(names, scores): print(f"{name}: {score}")
python id="py10_ex6" # 2D list (matrix) matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
print(matrix[0][0]) # 1 print(matrix[1][2]) # 6
# Print matrix for row in matrix: for val in row: print(f"{val:3}", end="") print()
python id="py10project" todos = []
print("=" * 40) print(" 📝 TO-DO LIST APP") print("=" * 40)
while True:
print("\n 1. Add task")
print(" 2. View tasks")
print(" 3. Remove task")
print(" 4. Exit")
choice = input("\n Choose (1-4): ")
if choice == "1":
task = input(" Enter task: ")
todos.append(task)
print(f" ✅ '{task}' added!")
elif choice == "2":
if not todos:
print(" 📭 No tasks yet!")
else:
print("\n Your Tasks:")
for i, task in enumerate(todos, 1):
print(f" {i}. {task}")
elif choice == "3":
if not todos:
print(" 📭 No tasks to remove!")
else:
idx = int(input(" Task number to remove: ")) - 1
if 0 <= idx < len(todos):
removed = todos.pop(idx)
print(f" 🗑️ '{removed}' removed!")
else:
print(" ❌ Invalid number!")
elif choice == "4":
print(" 👋 Goodbye!")
break
else:
print(" ❌ Invalid choice!")
``
---
9. Common Mistakes
- 1. Modifying list while iterating: Use a copy or list comprehension instead.
-
2.
Confusing append()
andextend():append adds one item; extend adds all items from iterable.
-
3.
Using =
for copying:b = acreates a reference, not a copy. Useb = a.copy().
-
4.
Index out of range: Always check len()
before accessing by index.
---
10. MCQs with Answers
Q1: Lists are: A) Immutable B) Mutable C) Fixed-size D) Type-restricted Answer: B
Q2: [1,2,3].append([4,5]) results in:
A) [1,2,3,4,5] B) [1,2,3,[4,5]] C) Error D) [1,2,3,4]
Answer: B — append adds the list as a single element.
Q3: [1,2,3][-1] returns:
A) 1 B) 2 C) 3 D) Error
Answer: C
Q4: len([1, [2, 3], 4]) returns:
A) 4 B) 3 C) 5 D) Error
Answer: B — Three elements: 1, [2,3], 4.
Q5: sorted() vs sort()?
A) Same B) sorted() returns new list C) sort() returns new list D) Neither
Answer: B
Q6: [x2 for x in range(4)] returns:
A) [0,1,4,9] B) [1,4,9,16] C) [0,2,4,6] D) [1,2,3,4]
Answer: A
Q7: To copy a list: A) b = a B) b = a.copy() C) b = a[:] D) Both B and C Answer: D
Q8: [1,2,3].pop(1) returns:
A) 1 B) 2 C) 3 D) [1,3]
Answer: B — Removes and returns element at index 1.
Q9: [1,2]+[3,4] returns:
A) [1,2,3,4] B) [[1,2],[3,4]] C) Error D) [4,6]
Answer: A
Q10: [1,2,3]*2 returns:
A) [2,4,6] B) [1,2,3,1,2,3] C) [[1,2,3],[1,2,3]] D) Error
Answer: B
---
11. Interview Questions
- 1. Difference between list and tuple? Lists are mutable; tuples are immutable.
-
2.
How to remove duplicates? list(set(mylist))
— but loses order. Uselist(dict.fromkeys(my_list))to preserve order.
-
3.
What are list comprehensions? Concise syntax to create lists: [expr for item in iterable if condition]
.
- 4. Difference between shallow and deep copy? Shallow copy copies references; deep copy copies everything recursively.
- 5. Time complexity of list operations? append: O(1), insert: O(n), access: O(1), search: O(n).
---
12. Summary
- Lists are ordered, mutable collections that can hold any type.
- Use indexing and slicing to access elements.
-
Key methods: append()
,insert(),remove(),pop(),sort(),reverse()`.
- List comprehensions provide concise syntax for creating lists.
- Nested lists represent matrices and multi-dimensional data.
---
13. Next Chapter Recommendation
In Chapter 11: Tuples and Sets**, you'll learn about immutable tuples and unique-element sets! 🚀