Lesson 6 · CS 111: Programming I — Python · OKSTEM College
Lists
A list is an ordered, mutable sequence that can hold any mix of types.
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", True, 3.14]
empty = []
# Indexing (0-based)
fruits[0] # "apple"
fruits[-1] # "cherry" (last element)# Common operations
fruits.append("date") # add to end
fruits.insert(1, "avocado") # insert at index 1
fruits.remove("banana") # remove first match
popped = fruits.pop() # remove & return last
fruits.sort() # sort in placelen(fruits) # number of elements"apple"in fruits # True/False membership
Slicing
Slicing extracts a portion of a sequence: seq[start:stop:step]. Stop is exclusive.
nums = [0, 1, 2, 3, 4, 5]
nums[1:4] # [1, 2, 3] - indices 1,2,3
nums[:3] # [0, 1, 2] - from start
nums[3:] # [3, 4, 5] - to end
nums[::2] # [0, 2, 4] - every 2nd
nums[::-1] # [5, 4, 3, 2, 1, 0] - reversed
nums[1:5:2] # [1, 3] - indices 1,3
Slices never raise IndexError even if the bounds exceed the list length. nums[100:200] on a 6-element list just returns [].
List Comprehensions
A concise way to build lists from existing sequences:
# squares of 0-9
squares = [x**2for x inrange(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]# only even squares
even_sq = [x**2for x inrange(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]# uppercase all words
words = ["hello", "world"]
upper = [w.upper() for w in words]
# ["HELLO", "WORLD"]
Tuples
Tuples are like lists but immutable (cannot be changed after creation). Use parentheses.
point = (3, 7) # x, y coordinate
rgb = (255, 128, 0) # color# Tuple unpacking
x, y = point
r, g, b = rgb
# Single-element tuple needs trailing comma
one = (42,) # without comma: just parentheses around 42
Use tuples for data that shouldn't change (coordinates, RGB values, function returns of multiple values). They're also slightly faster than lists and can be used as dictionary keys.
Practice Problems
Problem 1 - Remove duplicates preserving order
Write a function that takes a list and returns a new list with duplicates removed but original order preserved.
defremove_dupes(lst):
seen = []
return [x for x in lst if x not in seen andnot seen.append(x)]
# Cleaner alternative:defremove_dupes2(lst):
result = []
for item in lst:
if item not in result:
result.append(item)
return result
Problem 2 - Flatten a 2D list
Given matrix = [[1,2,3],[4,5,6],[7,8,9]], produce [1,2,3,4,5,6,7,8,9] using a list comprehension.
matrix = [[1,2,3],[4,5,6],[7,8,9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
The nested comprehension reads: "for each row in matrix, for each num in that row, give me num".
Knowledge Check
What does [1,2,3][-1] return?
Index -1 means last, not first.
Negative indexing is valid Python.
Correct - -1 is the last element.
None is returned for functions without return, not for indexing.
Quick Recap
Negative indices count from the end. -1 is the last element, -2 is second-to-last, etc. So [1,2,3][-1] = 3.
Quick Recap
Python supports negative indices natively. -1 = last, -2 = second-to-last. No error.
Quick Recap
Indexing always returns the element or raises IndexError. It never returns None.
What is the difference between a list and a tuple?
Tuples are actually slightly faster.
Correct.
Both hold any types.
Tuples use parentheses (), braces {} are for dicts/sets.
Quick Recap
Tuples are slightly more memory-efficient and faster to iterate. But the key difference is mutability.
Quick Recap
Both list and tuple can hold any mix of types. The difference is that list can be modified after creation, tuple cannot.
Quick Recap
Lists: [], Tuples: (), Dicts/Sets: {}.
What does [0,1,2,3,4][1:3] return?
The slice starts at index 1, not 0.
Correct - indices 1 and 2 (stop is exclusive).
Stop index 3 is exclusive - index 3 is not included.
The slice starts at index 1, not 0.
Quick Recap
slice[start:stop] - start=1 so we begin at index 1. stop=3 means up to (not including) index 3.
Quick Recap
slice stop is exclusive. [1:3] gives indices 1,2 only. To include index 3 you'd write [1:4].
Quick Recap
start=1 means begin at index 1 (value 1). The result is [1, 2].
Which creates a list of squares of even numbers from 0-9?
This includes all numbers, not just even ones.
Correct - the if clause filters for even x.
The if filter must come after the for clause.
This filters the squares, but keeps only even squares, not squares of even numbers.
Quick Recap
This creates squares of 0-9 (all of them). To filter for even, add: if x % 2 == 0.
Quick Recap
Syntax: [expression for item in iterable if condition]. The filter if comes last.
Quick Recap
This filters squares that happen to be even numbers, which is different from squaring the even numbers 0,2,4,6,8.
What happens when you try to do t = (1,2,3); t[0] = 99?
Tuples are immutable - this will fail.
Correct - tuples are immutable.
Python raises an error, it doesn't silently ignore it.
Python does not auto-convert types.
Quick Recap
Tuples cannot be modified after creation. Attempting assignment raises TypeError.
Quick Recap
Python does not silently ignore the assignment. It raises TypeError: 'tuple' object does not support item assignment.
Quick Recap
Python is strongly typed - it doesn't convert between types automatically. Use list(t) explicitly if you need a mutable copy.