Python Unit 5 - Data Structures

0.0(0)
Studied by 0 people
call kaiCall Kai
Locked
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/26

encourage image

There's no tags or description

Looks like no tags are added yet.

Last updated 1:32 AM on 7/29/26
Name
Mastery
Learn
Test
Matching
Spaced
Call with Kai
Chat

No analytics yet

Send a link to your students to track their progress

27 Terms

1
New cards

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]

2
New cards

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 cherry

3
New cards

List 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)

4
New cards

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]

5
New cards

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]

6
New cards

append

  • lst.append(val): Adds val to the end of the list.

7
New cards

insert

  • lst.insert(idx, val): Inserts val at idx, shifting current elements right.

8
New cards

pop

  • lst.pop(idx=-1): Removes and returns element at idx (default is last item). Throws error if out of bounds.

9
New cards

remove

  • lst.remove(val): Finds and removes the first occurrence of val. Throws ValueError if not present.

10
New cards

index

  • lst.index(val): Returns index of first occurrence of val (raises error if missing).

11
New cards

count

  • lst.count(val): Returns frequency of val.

12
New cards

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.

13
New cards

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: 6

14
New cards

Iterating & 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!

15
New cards

add

s.add(val): Adds val to set (ignored if already present).

16
New cards

remove

s.remove(val): Removes val. Raises KeyError if val is missing.

17
New cards

discard

s.discard(val): Removes val. Does NOT raise an error if val is missing.

18
New cards

clear

s.clear(): Empties the set completely, leaving set().

19
New cards

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)

20
New cards

union

Union (a.union(b)): Combines all unique elements from both sets (Reversible: a.union(b) == b.union(a)).

21
New cards

Intersection

Intersection (a.intersection(b)): Returns only elements contained in both sets (Reversible: a.intersection(b) == b.intersection(a)).

22
New cards

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)).

23
New cards

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 assignment

24
New cards

Tuple 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: 4

25
New cards

Dictionary 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"
}

26
New cards

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}")

27
New cards

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'}