1/26
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced | Call with Kai | Chat |
|---|
No analytics yet
Send a link to your students to track their progress
Data Structure and Collection Properties
A collection (or data structure) is a group of related data stored together in a single variable. A list is an ordered, indexed, mutable (changeable) collection of values defined inside square brackets [].
# List storing an integer, integer, boolean, string, and float
my_list = [5, 9, True, "Computer", 3.2]Positive and Negative Indexing
Positive Indexing: Elements are indexed from left to right starting at 0 and ending at len(list) - 1.
Negative Indexing: Elements are indexed from right to left starting at -1 (the last item) down to -len(list) (the first item).
fruits = ['apple', 'banana', 'cherry', 'date', 'eggplant']
print(fruits[0], fruits[-5]) # Output: apple apple
print(fruits[4], fruits[-1]) # Output: eggplant eggplant
print(fruits[2], fruits[-3]) # Output: cherry cherryList Functions vs. List Methods Syntax
Functions: Standalone procedures called with the syntax function_name(list_obj).
Methods: Object-attached operations called using dot notation: list_obj.method_name().
len(lst): Returns element count.
sum(lst): Totals numeric items.
min(lst) / max(lst): Finds smallest/largest values.
sorted(lst, reverse=False): Returns a new sorted list without modifying the original.
nums = [83, 24, 65, 99, 41]
print(len(nums)) # Output: 5
print(sum(nums)) # Output: 312
print(sorted(nums)) # Output: [24, 41, 65, 83, 99]
print(nums) # Output: [83, 24, 65, 99, 41] (Original unchanged)Modifying Lists (sort, reverse, clear, split)
lst.sort(reverse=False): Rearranges elements of the original list in-place (lexicographically for strings based on ASCII, placing capitalized words before lowercase).
lst.reverse(): Flips the order of elements in-place.
lst.clear(): Empties all elements from the list, leaving [].
str.split(sep=" "): String method that breaks a string into a list of strings split by a delimiter (default is space).
words = ["Cotton-Eyed", "Joe", "been"]
words.sort()
print(words) # Output: ['Cotton-Eyed', 'Joe', 'been'] (Capitalized first)
nums = [83, 24, 65]
nums.reverse()
print(nums) # Output: [65, 24, 83]Element Mutation
(append, insert, pop, remove, index, count)
nums = [99, 22, 35, 12]
nums.append(24) # [99, 22, 35, 12, 24]
nums.insert(2, 77) # [99, 22, 77, 35, 12, 24]
nums.pop(2) # Removes 77 -> [99, 22, 35, 12, 24]
nums.remove(12) # Removes 12 -> [99, 22, 35, 24]append
lst.append(val): Adds val to the end of the list.
insert
lst.insert(idx, val): Inserts val at idx, shifting current elements right.
pop
lst.pop(idx=-1): Removes and returns element at idx (default is last item). Throws error if out of bounds.
remove
lst.remove(val): Finds and removes the first occurrence of val. Throws ValueError if not present.
index
lst.index(val): Returns index of first occurrence of val (raises error if missing).
count
lst.count(val): Returns frequency of val.
Parallel Lists and the map() Function
Parallel lists are two or more lists where elements at matching indices correspond to each other. The map(func, iterable) function applies a transformation function/lambda across every item, returning a map object that can be converted back to a list via list().
x = [-2, -1, 0, 1, 2]
# Linear transformation: y = 3x - 4
y = list(map(lambda val: 3 * val - 4, x))
for i in range(len(x)):
print(f"({x[i]}, {y[i]})") # Prints coordinates (-2, -10), (-1, -7), etc.Sets and Properties
A set is an unordered, unindexed, mutable collection enclosed in curly braces {} that disallows duplicate values. Any added duplicate values are automatically dropped/ignored.
set_b = {1, 1, 2, 6, 2, 9, 5, 4}
print(set_b) # Output: {1, 2, 4, 5, 6, 9} (Duplicates removed)
print(len(set_b)) # Output: 6Iterating & Modifying Sets
(add, remove, discard, clear)
Iteration: Counter loops (range(len())) cannot be used because sets lack indices; only for-each loops (for val in my_set:) are valid.
Python
set_a = {4, 1, 8, 2, 5, 7}
set_a.add(6) # Set now has 6
set_a.discard(99) # No error raised even though 99 isn't in set
# set_a.remove(99) # Would throw KeyError!add
s.add(val): Adds val to set (ignored if already present).
remove
s.remove(val): Removes val. Raises KeyError if val is missing.
discard
s.discard(val): Removes val. Does NOT raise an error if val is missing.
clear
s.clear(): Empties the set completely, leaving set().
Set Operations
(union, intersection, difference)
set_g = {9, 3, 4, 1, 6, 2}
set_h = {1, 5, 4, 8, 6, 7}
print(set_g.union(set_h)) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(set_g.intersection(set_h)) # Output: {1, 4, 6}
print(set_g.difference(set_h)) # Output: {9, 2, 3} (In g, but not h)
print(set_h.difference(set_g)) # Output: {8, 5, 7} (In h, but not g)union
Union (a.union(b)): Combines all unique elements from both sets (Reversible: a.union(b) == b.union(a)).
Intersection
Intersection (a.intersection(b)): Returns only elements contained in both sets (Reversible: a.intersection(b) == b.intersection(a)).
difference
Difference (a.difference(b)): Returns elements present in set a that are NOT in set b (NOT reversible: a.difference(b) != b.difference(a)).
Tuple
Ordered, indexed, immutable collection defined within parentheses () that allows duplicate values. Once declared, elements cannot be added, removed, updated, or reordered.
my_tup = (6, 3, 4, 1, 8, 5)
print(my_tup[0]) # Output: 6
# my_tup[0] = 10 # ERROR! Tuples do not support item assignmentTuple Operations, Functions, & Methods
Type Conversion: Can convert lists/sets to tuples via tuple(iterable). An empty tuple is ().
Functions: Supports len(), sum(), min(), max().
Methods: Limited to non-modifying methods: tup.count(val) (counts occurrences) and tup.index(val) (returns first index of val).
my_tup = (1, 2, 6, 3, 7, 4, 3, 7, 2, 9, 4, 2, 8)
print(len(my_tup)) # Output: 13
print(my_tup.count(2)) # Output: 3
print(my_tup.index(7)) # Output: 4Dictionary Structure & Uniqueness
A dictionary is a mutable collection of key:value pairs enclosed in curly braces {}. Keys replace numeric indices and are usually strings.
car = {
"make": "Dodge",
"model": "Charger",
"year": 1971,
"color": "black"
}Iterating Through Dictionaries
Counter loops cannot be used directly. By default, iterating over a dictionary yields its keys.
for k in dict: Iterates through keys.
for v in dict.values(): Iterates through values.
for k, v in dict.items(): Iterates through key-value pairs simultaneously.
dc = {"make": "Dodge", "model": "Charger", "year": 1971}
# Keys only
for k in dc:
print(k, end=" ") # Output: make model year
# Values only
for v in dc.values():
print(v, end=" ") # Output: Dodge Charger 1971
# Keys and Values
for k, v in dc.items():
print(f"{k} -> {v}")Modifying, Adding, and Deleting Key-Value Entries
Access / Modify: dict[key] = new_val updates the value if key exists.
Add: dict[new_key] = val creates a new entry if new_key does not exist.
Delete (del vs pop): del dict[key] removes key and value. dict.pop(key) removes key and returns associated value (raises error if key missing).
dict.clear(): Empties all entries from dictionary.
len(dict): Returns number of key-value pairs.
dc = {"make": "Dodge", "model": "Charger", "year": 1971, "color": "black"}
dc["year"] = 2026 # Update existing key
dc["transmission"] = "automatic" # Add new key:value pair
dc.pop("color") # Removes "color" entry
del dc["make"] # Removes "make" entry
print(dc)
# Output: {'model': 'Charger', 'year': 2026, 'transmission': 'automatic'}