Learning outcomes
We will use Python 3 throughout this DSA course. Begin with Python’s core collection types and the different problems they solve.
By the end of this level
- Access list elements and string characters using indexes.
- Explain the difference between a list, set, and dictionary.
- Use a set for unique values and membership checks.
- Use a dictionary as Python’s Map type.
- Explain why a hash table is an implementation idea rather than a separate Python built-in type.
- Traverse sequences and understand references and copying.
Before you begin
Recognize variables, conditions, loops, and functions. Python uses indentation to group statements. Run examples in a Python 3 interpreter or save them in a .py file and run that file.
name = "Asha"
score = 70
if score >= 50:
print("Passed")
def double(value):
return value * 2
print(double(5))Passed 10
Each example is independent. Formal complexity analysis comes later; first, trace what the program does.
Why collections are useful
Separate mark variables work for five students, but become awkward for a whole class. A list groups values into one ordered, mutable sequence.
mark1 = 72
mark2 = 85
mark3 = 68
mark4 = 91
mark5 = 77
marks = [72, 85, 68, 91, 77]
print(marks)[72, 85, 68, 91, 77]
Many DSA resources call this topic “arrays.” In these Python lessons, we use the built-in list, a dynamic-array structure in CPython. Python also has an array module; NumPy provides another kind of array. Those are different types.
Lists can contain different types, but our beginner examples keep related values together, such as numbers or course names.
Choose a collection by its rule
A collection groups values, but different collections promise different behavior. Start with the requirement rather than choosing every collection as if it were a list.
| Python class | Conceptual contract | Main rule | How values are retrieved |
|---|---|---|---|
list | Sequence behavior | Ordered positions; duplicates allowed | By integer index |
set | Set ADT | Unique hashable elements | By membership, not index |
dict | Map ADT | Unique hashable keys associated with values | By key |
No HashTable built-in | Hash-table technique | Uses hashes and internal table positions | Used internally by set and dict |
Conceptual contract Concrete Python class Internal technique Set ADT → set → hash table Map ADT → dict → hash table Stack ADT → your Stack class → list or linked list
Set ADT and Map ADT are conceptual behavioral specifications. Python does not hand us those concepts as unimplemented declarations. It provides already implemented, usable classes: set implements Set behavior and dict implements Map behavior. A hash table describes the internal technique used by these classes in CPython.
Python set: unique values, no indexes
A Python set stores each equal value only once. It is useful for membership checks, removing duplicates, and comparing groups.
courses = {"Python", "DSA", "Python", "SQL"}
courses.add("Git")
courses.discard("SQL")
print(sorted(courses))
print("DSA" in courses)
print(len(courses))['DSA', 'Git', 'Python'] True 3
The duplicate "Python" does not create a second element. sorted() is used only to make the displayed result predictable.
Create an empty set correctly
Use set() for an empty set. Empty curly braces create a dictionary.
empty_set = set()
empty_dictionary = {}
print(type(empty_set).__name__)
print(type(empty_dictionary).__name__)set dict
| Set operation | Python syntax |
|---|---|
| Create from values | set(values) |
| Add one element | values.add(item) |
| Add several elements | values.update(items) |
| Remove safely | values.discard(item) |
Remove or raise KeyError | values.remove(item) |
| Check membership | item in values |
| Number of elements | len(values) |
| Remove everything | values.clear() |
A set is not indexed
numbers = {10, 20, 30}
try:
print(numbers[0])
except TypeError:
print("A set has no index 0")A set has no index 0
A set does not promise positional access. If you require “the first value” or values[2], use a list. Converting a set directly with list(numbers) produces a list, but you should not rely on which set element becomes index 0. Use sorted(numbers) when you need a defined sorted order.
Set operations
backend = {"Python", "SQL", "Git"}
data = {"Python", "SQL", "Pandas"}
print(sorted(backend | data)) # union
print(sorted(backend & data)) # intersection
print(sorted(backend - data)) # difference['Git', 'Pandas', 'Python', 'SQL'] ['Python', 'SQL'] ['Git']
Set elements must be hashable. Integers, strings, and suitable tuples can be elements. A list is mutable and cannot be placed directly inside a set.
Python dict: a concrete Map implementation
The Map ADT is the conceptual contract that associates keys with values. Python’s already implemented, concrete class for Map behavior is dict, short for dictionary.
Map ADT contract → Python dict class → usable dictionary objects "Asha" → 92 "Ravi" → 85 "Meena" → 88
scores = {
"Asha": 92,
"Ravi": 85,
"Meena": 88,
}
print(scores["Asha"])
scores["Ravi"] = 89
scores["John"] = 81
print(scores.get("Ravi"))
print(scores.get("Unknown", 0))92 89 0
The key "Asha" is not an integer position. It identifies its associated value. Assigning to an existing key updates its value; assigning to a new key creates a new entry.
| Operation | Meaning |
|---|---|
data[key] | Read the value; raise KeyError when the key is missing. |
data.get(key, default) | Read with a fallback for a missing key. |
data[key] = value | Add a new entry or update an existing one. |
key in data | Test whether the dictionary contains the key. |
data.items() | Visit key-value pairs. |
data.pop(key) | Remove a key and return its value. |
The contract is not another Python class
The Map ADT is the idea that defines the operations and their meaning. The dict class contains the actual implementation. You can create and use dictionary objects immediately; you do not need to subclass an abstract MapADT declaration.
Map is not Python’s map() function
In DSA, Map ADT means key-value storage. Python’s lowercase map(function, iterable) is a separate function that transforms iterable values. In this course, “map structure” means dict.
Frequency counting
words = ["red", "blue", "red", "green", "red"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts["red"])
print(counts["blue"])3 1
Each word is a key, and its occurrence count is the associated value.
Why use a hash table?
Imagine checking whether an employee name exists in a list. A list may need to compare names one by one until it finds a match.
employees = ["Asha", "Ravi", "Meena", "John"]
print("John" in employees)True
Asha → not equal Ravi → not equal Meena → not equal John → found
For n elements, this membership check can require up to n comparisons. A hash table uses a key’s hash to move toward a likely internal location instead of beginning with a complete sequential scan.
| Question | Suitable Python collection |
|---|---|
| What value is at position 3? | list |
| Has this unique value already appeared? | set |
| What value belongs to this key? | dict |
The hash table supports the last two questions internally. It does not replace lists when positional indexing is required.
Hash table: how lookup is supported
Python does not provide a core class named HashTable. A hash table is the implementation technique used for Python dictionaries and sets in CPython and other common implementations.
key → hash(key) → internal table location → stored entry set entry: key dictionary entry: key + associated value
Python calls hash(key) to obtain an integer hash value. The implementation uses that value to help locate an internal table position. You do not use the hash as a list index yourself.
student_id = "EMP-104"
print(isinstance(hash(student_id), int))
print(hash(student_id) == hash(student_id))True True
The exact hash value can differ between Python processes, especially for strings. Code should use hashes for equality-compatible lookup, never as permanent IDs.
What if two keys lead to the same area?
That situation is a collision. A correct hash table checks keys and resolves collisions internally. Two different keys are still allowed to coexist.
Why must keys be hashable?
A key’s hash must remain stable while it is stored. Mutable lists can change their contents, so Python rejects them as dictionary keys and set elements.
valid = {
"name": "Asha", # string key
101: "employee", # integer key
(2, 4): "position", # hashable tuple key
}
try:
invalid = {[1, 2]: "list key"}
except TypeError:
print("Lists are unhashable")Lists are unhashable
| Layer | What it represents |
|---|---|
| Set ADT | Conceptual contract: unique membership behavior. |
| Map ADT | Conceptual contract: key-value association behavior. |
Python set | Concrete, already implemented class for Set behavior. |
Python dict | Concrete, already implemented class for Map behavior. |
| Hash table | Internal implementation technique supporting lookup. |
Stage 1 focuses on correct usage and the mental model. Stage 2 analyzes average and worst cases, collisions, table resizing, load factor, and comparisons with balanced trees.
From a key to an internal position
A simplified teaching model starts with an internal table containing numbered positions, sometimes called slots or buckets.
key → hash(key) → choose an internal table position → check stored entry
For a small imaginary table, a lesson might demonstrate hash(key) % table_size. Real CPython dictionaries and sets use more sophisticated rules, so application code should never calculate or depend on the internal position.
key = "Asha"
hash_value = hash(key)
print(isinstance(hash_value, int))
print(hash_value == hash(key))True True
The same unchanged key produces the same hash during one execution. String hashes can differ between Python processes, so a hash value must not be stored as a permanent identifier.
set entry → key dictionary entry → key + associated value
Collisions and equality checks
Different keys can initially lead toward the same table area. This is a collision. A correct hash table resolves the collision and stores both entries.
key A ─┐
├──▶ same initial area ──▶ probe other positions and compare keys
key B ─┘Common strategies are chaining, which groups entries in a bucket, and open addressing, which probes other table positions. CPython dictionaries and sets use an open-addressing style.
Python does not trust the hash alone. It uses hash information to narrow the search and equality to confirm the key.
class Example:
def __init__(self, value):
self.value = value
def __hash__(self):
return 10
def __eq__(self, other):
return isinstance(other, Example) and self.value == other.value
first = Example("A")
second = Example("B")
print(hash(first) == hash(second))
print(first == second)
print(len({first, second}))True False 2
Both objects deliberately have the same hash, but they are unequal and remain separate set elements. Therefore, equal hashes do not prove equal values.
If a == b, then hash(a) must equal hash(b). The reverse is not required: equal hashes may belong to unequal values.
Hashable and unhashable objects
Dictionary keys and set elements must be hashable. Their hash and equality behavior must remain suitable while they are stored.
| Usually hashable | Usually unhashable |
|---|---|
| Integers | Lists |
| Strings | Dictionaries |
| Tuples containing only hashable elements | Sets |
frozenset | Tuples containing an unhashable element |
Lists are mutable. If a list changed after being placed into a hash table, the new contents could imply a different lookup location while the entry remained stored in the old location. Python prevents that problem by making lists unhashable.
valid_key = (10, 20, "Python")
print(isinstance(hash(valid_key), int))
try:
invalid_key = (10, [20, 30])
hash(invalid_key)
except TypeError:
print("The tuple contains an unhashable list")True The tuple contains an unhashable list
A tuple is not automatically hashable; every object inside it must also be hashable.
Order, table space and resizing
Modern Python dictionaries preserve insertion order when iterated. That logical order is separate from the internal hash-table positions.
employee = {}
employee["name"] = "Asha"
employee["age"] = 30
employee["city"] = "Hyderabad"
print(list(employee))['name', 'age', 'city']
Insertion order does not mean keys are sorted. A set provides no positional indexing or sequence-order contract that application code should rely on.
Why tables need unused space
A crowded table produces more collisions and probing. Python automatically creates a larger internal table and relocates entries when necessary. This operation is called resizing.
load factor = stored entries ÷ available table positions more free space → fewer probes on average very crowded → more collisions and probes
Python manages the capacity, load factor, and resizing automatically. These are implementation concerns rather than methods you call on dict or set.
Performance and practical use
Hash tables are chosen because key lookup and membership are usually constant-time operations on average. Formal proofs and implementation analysis come in Stage 2.
| Operation | List | Set | Dictionary |
|---|---|---|---|
| Membership | O(n) | O(1) average | O(1) average for keys |
| Read by integer index | O(1) | Not supported | Not positional |
| Read by key | Not a key-value structure | No associated value | O(1) average |
| Add | Append is amortized O(1) | O(1) average | O(1) average |
| Remove by value or key | Usually O(n) | O(1) average | O(1) average |
In extreme collision situations, a hash-table operation can approach O(n). “Constant time” here means the expected average case, not an unconditional guarantee.
Duplicate detection and frequency counting
values = [2, 4, 2, 6, 4, 8, 10, 8]
seen = set()
duplicates = set()
frequencies = {}
for value in values:
if value in seen:
duplicates.add(value)
seen.add(value)
frequencies[value] = frequencies.get(value, 0) + 1
print(sorted(duplicates))
print(frequencies)[2, 4, 8]
{2: 2, 4: 2, 6: 1, 8: 2, 10: 1}seen → set → Have I seen this value? duplicates → set → Which repeated values exist? frequencies → dict → How many times did each value appear?
Remember: a set answers whether a unique value exists; a dictionary finds a value using a key; a hash table is the internal data structure supporting those lookups efficiently.
Dictionary versus hash table
A dictionary is the key-value collection interface that a programmer uses. A hash table is the internal data structure and technique that can implement that interface.
Dictionary operation → hash(key) → table position → stored key + value
| Concept | Role |
|---|---|
| Dictionary | User-facing key-value collection with operations such as read, insert, update, delete and membership. |
| Hash table | Internal structure with buckets, hashing, collision handling, load factor and resizing. |
| Map ADT | The abstract behavior that a dictionary promises. |
In Python, dict uses hash-table techniques, so key lookup is usually O(1) on average. The dictionary hides buckets and collisions; you use keys and values rather than internal positions.
student_marks = {"Asha": 91, "Ravi": 78}
print(student_marks["Asha"])
print("Ravi" in student_marks)91 True
The implementation could be different
A dictionary-like Map could also be implemented with a balanced search tree. That version would usually provide O(log n) lookup instead of average O(1). The name describes the behavior; the hash table describes one implementation choice.
Remember: a hash table is not another Python built-in collection beside dict. It is the technique commonly used underneath dictionaries and sets.
Elements, indexes and length
An element is a stored value. Its index identifies its position. Indexes start at zero, so the third element has index 2.
marks = [72, 85, 68, 91, 77]
print(marks[0])
print(marks[2])
print(len(marks))
print(marks[len(marks) - 1])
print(marks[-1])72 68 5 77 77
len(marks) gives the number of elements. The last nonnegative index of a nonempty list is len(marks) - 1. Python also supports negative indexes: -1 is the last element and -2 is the second-last.
Empty lists and invalid indexes
values = []
print(len(values))
try:
print(values[0])
except IndexError:
print("No element at index 0")0 No element at index 0
An out-of-range index raises IndexError. It does not return a default value or None. An empty list has no valid element index, including -1.
Updating a list
Replace an element using its index. This changes a value without changing the list length.
marks = [72, 85, 68]
marks[1] = 90
print(marks)[72, 90, 68]
Add and remove at the end
append() adds one element at the end. pop() removes and returns the last element.
values = [10, 20]
values.append(30)
print(values)
removed = values.pop()
print(removed)
print(values)[10, 20, 30] 30 [10, 20]
Calling pop() on an empty list raises IndexError. Check the list when emptiness is possible.
values = []
if values:
print(values.pop())
else:
print("Nothing to remove")Nothing to remove
Changing an element versus replacing a list
values = [10, 20]
values[0] = 99 # Mutates this list
values = [40, 50] # Rebinds the name to a different list
print(values)[40, 50]
List elements can be changed after creation. Assigning to an out-of-range list index raises IndexError; use append() to add an element.
Traversing a list
Traversal means visiting elements systematically. When you need only values, iterate directly.
marks = [72, 85, 68]
for mark in marks:
print(mark)72 85 68
Visit indexes
marks = [72, 85, 68]
for i in range(len(marks)):
print(i, marks[i])0 72 1 85 2 68
produces 0, 1, 2. Its stop value is excluded. Select the function whenever you need a quick Python refresher.
| Iteration | i | marks[i] |
|---|---|---|
| 1 | 0 | 72 |
| 2 | 1 | 85 |
| 3 | 2 | 68 |
Using would eventually access an invalid index and raise IndexError.
Get indexes and values together
names = ["Asha", "Ravi", "Meena"]
for i, name in enumerate(names):
print(i, name)0 Asha 1 Ravi 2 Meena
Traverse backwards
values = [10, 20, 30]
for value in reversed(values):
print(value)
print(values)30 20 10 [10, 20, 30]
reversed() changes visiting order without changing the original list. If you need indexes, use:
values = [10, 20, 30]
for i in range(len(values) - 1, -1, -1):
print(i, values[i])2 30 1 20 0 10
The arguments are start, excluded stop, and step. Starting at the last index, we step backwards and stop before -1. Avoid adding or removing list elements while learning traversal.
Strings as sequences
Python strings represent Unicode text. Like lists, they support indexing, len(), and iteration.
course = "DSA"
print(course[0])
print(course[-1])
print(len(course))
for character in course:
print(character)D A 3 D S A
Strings are immutable
You cannot replace a character by assigning to an index. Doing so raises TypeError. Build a new string instead.
word = "cat"
# word[0] = "b" # Would raise TypeError
word = "b" + word[1:]
print(word)bat
word[1:] is a slice containing the text from index 1 onward: "at". The name is rebound to a new string; the old string is not modified.
String indexing and length operate on Unicode code points. A visible character can contain multiple code points, so visible-character counting needs more care. We use simple text for this level.
Values and references
In Python, names refer to objects. Assignment binds a name to an object; it does not automatically copy that object.
Rebinding a number
first = 10
second = first
second = 99
print(first)
print(second)10 99
Integers are immutable. Rebinding second does not change the integer object referred to by first.
Sharing a mutable list
first = [10, 20, 30]
second = first
second[0] = 99
print(first)
print(second)[99, 20, 30] [99, 20, 30]
Both names refer to the same list object. Mutating it is visible through either name.
second ↗[10, 20, 30]
Both names point to one list.
Rebinding is different from mutation
first = [10, 20]
second = first
second = [70, 80]
print(first)
print(second)[10, 20] [70, 80]
Now second refers to a different list. The original list is unchanged.
Copying a list
Use copy() to create a new outer list. For numbers or strings, changing an element of the copy leaves the original list unchanged.
original = [10, 20, 30]
copy = original.copy()
copy[0] = 99
print(original)
print(copy)
print(original == copy)
print(original is copy)[10, 20, 30] [99, 20, 30] False False
original[:] is another way to make a shallow list copy.
Equality and identity
== compares values. is checks whether two names refer to the same object. Use == when comparing contents.
a = [1, 2]
b = a.copy()
print(a == b)
print(a is b)True False
A shallow copy has limits
Objects inside the list are not recursively copied. These two lists share the same nested dictionary.
original = [{"name": "Asha"}]
copy = original.copy()
copy[0]["name"] = "Meena"
print(original[0]["name"])Meena
The outer lists are different objects, but their first elements still refer to the same dictionary. That is why changing the dictionary through copy also affects original.
Deep copy nested objects
Import Python’s copy module and call copy.deepcopy(value). A deep copy recursively creates independent copies of the outer container and the mutable objects nested inside it.
import copy
original = [{"name": "Asha", "scores": [72, 85]}]
independent = copy.deepcopy(original)
independent[0]["name"] = "Meena"
independent[0]["scores"][0] = 99
print(original)
print(independent)
print(original is independent)
print(original[0] is independent[0])[{'name': 'Asha', 'scores': [72, 85]}]
[{'name': 'Meena', 'scores': [99, 85]}]
False
FalseThe original nested dictionary and score list remain unchanged. Both the outer list and its nested mutable objects are now independent.
Shallow copy or deep copy?
| Situation | Recommended choice |
|---|---|
| A flat list of numbers or strings | Use list.copy() or slicing. |
| Nested mutable lists, dictionaries or sets must change independently | Use copy.deepcopy(). |
| Nested data is intentionally shared | Use a shallow copy and document the sharing. |
Deep copying can use more time and memory because Python visits the nested object structure. It also does not make immutable objects such as integers or strings mutable. Choose it when independent nested mutation is required, rather than using it automatically for every copy.
Lists passed to functions
A function parameter is a local name bound to the supplied object. Mutating that shared object is visible to the caller.
def update_first(values):
if values:
values[0] = 99
numbers = [10, 20, 30]
update_first(numbers)
print(numbers)[99, 20, 30]
Rebinding the local parameter does not rebind the caller’s name.
def replace_list(values):
values = [99, 100]
numbers = [10, 20]
replace_list(numbers)
print(numbers)[10, 20]
To give a new list back to the caller, return it and explicitly assign the result:
def replacement():
return [99, 100]
numbers = [10, 20]
numbers = replacement()
print(numbers)[99, 100]
Guided practice
Try the tasks first. Open each solution when you are ready to compare.
A: Print indexes and values for [15, 25, 35]. B: Print CODE backwards, one character per line. C: Copy a list and replace its second element without changing the original.
A · Print indexes and values
values = [15, 25, 35]
for i, value in enumerate(values):
print(i, value)0 15 1 25 2 35
B · Print a string backwards
word = "CODE"
for character in reversed(word):
print(character)E D O C
C · Update a copy
original = [10, 20, 30]
copy = original.copy()
copy[1] = 200
print(original)
print(copy)[10, 20, 30] [10, 200, 30]
Independent exercises
Solve these independently and explain your reasoning aloud.
- Create five course names. Print the length, first element, and last element.
- Remove duplicates from eight course names with a set, then display them in sorted order.
- Create a dictionary mapping five course names to durations. Read, update, add, and remove entries.
- Count repeated words with a dictionary.
- Explain why a set does not support values[0].
- Explain why a list cannot be a dictionary key.
- Print each course name with its index using enumerate().
- Visit list elements backwards without changing the list.
- Bind two names to one list. Mutate it and explain both outputs.
- Repeat with copy() to create an independent outer list.
- Write a function that prints a list without modifying it.
Predict the output
Write your predictions before revealing the answers.
# A
values = [4, 8, 12]
print(values[-1])
try:
print(values[len(values)])
except IndexError:
print("IndexError")# B
a = [1, 2]
b = a
b.append(3)
print(len(a))
print(a is b)# C — a separate example
a = [1, 2]
b = a.copy()
print(a == b)
print(a is b)
b.append(3)
print(len(a))
print(len(b))Reveal answers and explanations
| Example | Output | Why |
|---|---|---|
| A | 12, IndexError | Negative indexing accesses the last element; len(values) is out of range. |
| B | 3, True | Both names refer to the same list. |
| C | True, False, 2, 3 | Initially equal contents, but distinct list objects. Only b grows. |
Check your understanding
| Misconception | Correction |
|---|---|
| Python provides an abstract SetADT class. | Python provides the concrete, usable set class that implements Set behavior. |
| Python provides an abstract MapADT class. | Python provides the concrete, usable dict class that implements Map behavior. |
| A set is a list without duplicates. | A set provides uniqueness and membership, but no positional indexing. |
| Map means Python’s map() function. | In DSA, the Map ADT is the key-value behavioral contract; dict is its concrete Python implementation. |
| A dictionary key is an index. | A key identifies an associated value and need not be numeric. |
| Hash table is another Python core type. | It is an implementation technique underlying dict and set behavior. |
| Different keys can never have the same hash area. | Collisions are possible and are resolved internally. |
| Any Python object can be a set element or dictionary key. | Keys and set elements must be hashable. |
| Assignment creates a list copy. | It binds another name to the same object. |
| Strings can be changed by index. | Strings are immutable. |
| copy() recursively copies everything. | It is a shallow copy. |
Your completion gate
Check these only when you can demonstrate them independently. This checklist is saved in this browser.