0% found this document useful (0 votes)
4 views11 pages

Python Data Structures Guide

The document provides a comprehensive overview of Python data structures including Lists, Tuples, Sets, and Dictionaries, detailing their properties, syntax, and common operations. It includes examples of creating and manipulating each data structure, along with best practices and performance tips. Additionally, it offers guidance on when to use each structure based on specific use cases.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Python Data Structures Guide

The document provides a comprehensive overview of Python data structures including Lists, Tuples, Sets, and Dictionaries, detailing their properties, syntax, and common operations. It includes examples of creating and manipulating each data structure, along with best practices and performance tips. Additionally, it offers guidance on when to use each structure based on specific use cases.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Dream Big Technologies Sdn. Bhd.

Your Digital Growth Partner


Jalan 3/155, Bukit Jalil, Kuala Lumpur, 58200
[Link] | growwithus@[Link]

Python Data Structures


List | Tuple | Set | Dictionary

Quick Comparison
List [ ] Tuple ( ) Set { } Dict { k:v }
Ordered Yes Yes No Yes (3.7+)
Mutable Yes No Yes Yes
Duplicates Yes Yes No Keys: No
Indexable Yes Yes No By Key
Hashable No Yes No No
Use for Dynamic lists Fixed records Unique values Key-value maps
01 — List

List
An ordered, mutable collection that allows duplicate elements. It is the go-to data structure for any
collection you plan to add, remove, or modify over time.

Properties
Ordered Mutable Duplicates Indexable Syntax

Yes Yes Yes Yes []

Creating a List
# A shopping cart
cart = ["apple", "banana", "mango", "apple"]

print(cart[0]) # apple (first item)


print(cart[-1]) # apple (last item)
print(cart[1:3]) # ['banana', 'mango'] (slicing)

# Mixed types are allowed


mixed = [1, "hello", 3.14, True]

Common Operations
# --- Adding items ---
[Link]("grape") # add to the end
[Link](1, "cherry") # insert at index 1
[Link](["kiwi", "pear"]) # merge another list

# --- Removing items ---


[Link]("banana") # remove first occurrence by value
[Link]() # remove and return the last item
[Link](0) # remove and return item at index 0
[Link]() # empty the list

# --- Querying ---


len(cart) # number of items
[Link]("apple") # how many times it appears
[Link]("mango") # position of first occurrence
"apple" in cart # True/False membership check

# --- Sorting ---


[Link]() # in-place ascending
[Link](reverse=True) # in-place descending
sorted_cart = sorted(cart) # returns NEW sorted list

List Comprehension — Python's Superpower


nums = [1, 2, 3, 4, 5, 6, 7, 8]

# Filter even numbers


evens = [x for x in nums if x % 2 == 0]
# [2, 4, 6, 8]

# Square each number


squares = [x ** 2 for x in nums]
# [1, 4, 9, 16, 25, 36, 49, 64]

# Combine filter and transform


even_squares = [x**2 for x in nums if x % 2 == 0]
# [4, 16, 36, 64]

Iterating a List
fruits = ['apple', 'banana', 'mango']

# Simple iteration
for fruit in fruits:
print(fruit)

# With index
for i, fruit in enumerate(fruits):
print(i, fruit) # 0 apple, 1 banana, 2 mango

# Iterate two lists together


prices = [1.50, 2.00, 3.50]
for fruit, price in zip(fruits, prices):
print(f'{fruit}: RM{price:.2f}')

Senior Dev Tip: Prefer list comprehensions over for loops when building new lists — they run at C
speed inside CPython. For heavy prepend operations (insert at index 0), use [Link]
instead, which is O(1) vs list's O(n).
02 — Tuple

Tuple
An ordered, immutable collection that allows duplicates. Think of it as a frozen list — perfect for
data that should never change: coordinates, RGB colours, database rows, and function return
values.

Properties
Ordered Mutable Duplicates Indexable Syntax

Yes No Yes Yes ()

Creating a Tuple
# GPS coordinate — should never change
location = (3.1390, 101.6869) # Kuala Lumpur

# Indexing works just like a list


print(location[0]) # 3.139
print(location[-1]) # 101.6869

# IMPORTANT: single-item tuple needs a trailing comma


single = ("only_me",) # This is a tuple
not_tuple = ("only_me") # This is just a string!

# Empty tuple
empty = ()

Unpacking — The Killer Feature


rgb = (255, 128, 0)
r, g, b = rgb # clean destructuring
print(r) # 255

# Extended unpacking
first, *rest = (1, 2, 3, 4, 5)
# first = 1, rest = [2, 3, 4, 5]

# Swap without a temp variable


a, b = 10, 20
a, b = b, a # uses a tuple under the hood
print(a, b) # 20, 10
Returning Multiple Values from a Function
def get_stats(numbers):
return min(numbers), max(numbers), sum(numbers) / len(numbers)

lo, hi, avg = get_stats([3, 1, 9, 4, 7])


print(f'Min={lo}, Max={hi}, Avg={avg}') # Min=1, Max=9, Avg=4.8

Tuple as Dictionary Key


# Tuples are hashable → they CAN be dict keys
# Lists are NOT hashable → they CANNOT be dict keys

grid = {}
grid[(0, 0)] = "origin"
grid[(1, 2)] = "point A"
grid[(3, 4)] = "point B"

print(grid[(1, 2)]) # point A

Named Tuples — Best of Both Worlds


from collections import namedtuple

Point = namedtuple("Point", ["x", "y"])


p = Point(10, 20)

print(p.x) # 10 (attribute access)


print(p[0]) # 10 (index access still works)
print(p) # Point(x=10, y=20)

# Modern alternative: [Link]


from typing import NamedTuple
class Point(NamedTuple):
x: float
y: float

Senior Dev Tip: Tuples are faster to create and iterate than lists, and consume less memory. Use
them whenever immutability is a design guarantee. For production code with many fields, prefer
dataclasses (Python 3.7+) or NamedTuple for self-documenting structured data.
03 — Set

Set
An unordered, mutable collection of unique items. Sets shine for deduplication, fast membership
testing (O(1)), and set-math operations like union, intersection, and difference.

Properties
Ordered Mutable Duplicates Indexable Syntax

No Yes No No {}

Creating a Set
# Duplicates are silently removed
tags = {"python", "backend", "python", "api", "backend"}
print(tags) # {'python', 'backend', 'api'}

# From a list — the fastest way to deduplicate


names = ["Ali", "Bob", "Ali", "Sara", "Bob"]
unique_names = set(names) # {'Ali', 'Bob', 'Sara'}

# IMPORTANT: empty set — you MUST use set(), not {}


empty = set() # Correct
not_a_set = {} # This is an empty DICT!

Add and Remove Items


[Link]("django") # add one item
[Link]("api") # safe remove (no error if missing)
[Link]("python") # raises KeyError if missing

popped = [Link]() # remove and return a random item


[Link]() # remove all items

Membership Testing — O(1) Speed


allowed_roles = {"admin", "editor", "viewer"}

# Checking membership in a SET is O(1) — instant regardless of size


"admin" in allowed_roles # True
"hacker" in allowed_roles # False
# Checking in a LIST is O(n) — scans every element
# For 1,000,000 items, set check is ~1000x faster than list

Set Mathematics
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

a | b # Union: {1, 2, 3, 4, 5, 6}
a & b # Intersection: {3, 4}
a - b # Difference (a-b): {1, 2}
b - a # Difference (b-a): {5, 6}
a ^ b # Symmetric diff: {1, 2, 5, 6}

# Check relationships
[Link](b) # Is every item in a also in b?
[Link](b) # Does a contain all items of b?
[Link](b) # Do a and b share NO items?

Real-World Example — Common Users


# Find users who visited BOTH pages
page_a_visitors = {"u001", "u002", "u003", "u004"}
page_b_visitors = {"u002", "u003", "u005", "u006"}

common = page_a_visitors & page_b_visitors


# {"u002", "u003"}

only_a = page_a_visitors - page_b_visitors


# {"u001", "u004"}

all_visitors = page_a_visitors | page_b_visitors


# {"u001", "u002", "u003", "u004", "u005", "u006"}

Senior Dev Tip: Use frozenset when you need an immutable set (e.g. as a dict key or inside another
set). Deduplicating a million-item list? list(set(data)) is your best friend. For counting occurrences,
[Link] is even better.
04 — Dictionary

Dictionary
An ordered (Python 3.7+), mutable mapping of unique keys to values. The workhorse of Python
data — think JSON, lookup tables, counters, configs, and grouping.

Properties
Ordered Mutable Dup. Keys Dup. Values Syntax

Yes (3.7+) Yes No Yes {k: v}

Creating a Dictionary
# A user profile
user = {
"name": "Ahmad",
"age": 28,
"city": "Kuala Lumpur",
"skills": ["Python", "Django", "FastAPI"]
}

# Access by key — raises KeyError if missing


print(user["name"]) # Ahmad

# Safe access with .get() — returns default if missing


print([Link]("salary", 0)) # 0 (no KeyError!)

# Check if key exists


"age" in user # True
"salary" in user # False

Add, Update, Delete


# Add a new key
user["email"] = "ahmad@[Link]"

# Update an existing key


user["age"] = 29

# Delete a key
del user["city"]
# Safe delete — returns None if key missing (no error)
[Link]("salary", None)

# Delete and get the value


removed_age = [Link]("age")

Iterating a Dictionary
# Iterate over keys (default)
for key in user:
print(key)

# Iterate over values


for value in [Link]():
print(value)

# Iterate over key-value pairs (most common)


for key, value in [Link]():
print(f"{key} -> {value}")

Dictionary Comprehension
words = ["hi", "hello", "hey", "howdy"]
lengths = {w: len(w) for w in words}
# {'hi': 2, 'hello': 5, 'hey': 3, 'howdy': 5}

# Filter while building


long_words = {w: len(w) for w in words if len(w) > 3}
# {'hello': 5, 'howdy': 5}

# Invert a dictionary
original = {"a": 1, "b": 2, "c": 3}
inverted = {v: k for k, v in [Link]()}
# {1: 'a', 2: 'b', 3: 'c'}

Merging Dictionaries
# Python 3.9+ — the cleanest way
defaults = {"theme": "dark", "lang": "en", "timeout": 30}
overrides = {"lang": "ms", "timeout": 60}
config = defaults | overrides
# {'theme': 'dark', 'lang': 'ms', 'timeout': 60}

# Python 3.5+ — using ** unpacking


config = {**defaults, **overrides} # same result

# In-place merge
[Link](overrides)

Advanced — defaultdict & Counter


from collections import defaultdict, Counter

# defaultdict: no KeyError when key is missing


groups = defaultdict(list)
words = ["apple", "ant", "bear", "banana", "cat"]
for word in words:
groups[word[0]].append(word)
# {'a': ['apple', 'ant'], 'b': ['bear', 'banana'], 'c': ['cat']}

# Counter: count occurrences instantly


sentence = "the cat sat on the mat"
freq = Counter([Link]())
# Counter({'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1})
print(freq.most_common(2)) # [('the', 2), ('cat', 1)]

Nested Dictionary
company = {
"engineering": {"head": "Siti", "size": 12, "remote": True},
"marketing": {"head": "Reza", "size": 5, "remote": False},
}

# Accessing nested data


print(company["engineering"]["head"]) # Siti

# Safe nested access


print([Link]("hr", {}).get("head")) # None (no error)
When to Use Which?
Structure Best For Avoid When Real-World Example

List [ ] Ordered, changeable You need unique values only Shopping cart, user feed,
data task queue

Tuple ( ) Fixed, immutable records You need to add/remove GPS coords, DB row,
items func return

Set { } Unique values, fast You need order or duplicates Permission roles, tag
lookup dedup, visitors

Dict {k:v} Key-value mapping & You don't need named User profile, config, API
lookup access response

You might also like