🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to Data Analytics Notes
Topic #42

Python Data Structures

By the end of this lesson, you will be able to select and use Python's four core data structures—lists, dictionaries, sets, and tuples—to store and manipulate data efficiently in analytics workflows.

What it is

Python provides four primary built-in data structures for organizing collections of items. Lists are ordered, mutable sequences that allow duplicate values. Tuples are ordered, immutable sequences, often used for fixed records like coordinates or database rows. Dictionaries are unordered (in older versions) or insertion-ordered (Python 3.7+) key-value pairs, ideal for mapping identifiers to data. Sets are unordered collections of unique elements, perfect for membership testing and removing duplicates. Understanding these structures is fundamental because they form the backbone of data cleaning, transformation, and aggregation tasks in libraries like Pandas and NumPy.

Why it matters

  • Efficiency: Sets provide O(1) average-time complexity for membership checks, making them faster than lists for large datasets.
  • Data Integrity: Tuples ensure that critical configuration parameters or record keys cannot be accidentally modified.
  • Flexibility: Dictionaries allow rapid lookup by name or ID rather than index, simplifying code readability.
  • Cleaning: Lists and sets are essential for filtering out nulls, removing duplicates, and reshaping raw data arrays.

Syntax or steps

To create a list, use square brackets: [item1, item2]. For a tuple, use parentheses: (item1, item2). A dictionary uses curly braces with colons separating keys and values: {key1: value1}. A set uses curly braces without colons: {item1, item2}. Note that an empty set must be created using set(), as {} creates an empty dictionary.

Example

# Define different data structures
user_ids = [101, 102, 103, 101]          # List: allows duplicates, mutable
coordinates = (45.5, -122.6)             # Tuple: immutable, ordered
user_profiles = {                        # Dict: key-value mapping
    101: "Alice",
    102: "Bob"
}
unique_visitors = set(user_ids)          # Set: removes duplicates automatically

# Operations
print(f"Original IDs: {user_ids}")
print(f"Unique Visitors: {unique_visitors}")
print(f"Alice's Profile: {user_profiles[101]}")

# Attempting to modify a tuple raises an error
try:
    coordinates[0] = 46.0
except TypeError as e:
    print(f"Error modifying tuple: {e}")
Explanation: The list user_ids stores raw event data including duplicates. We convert it to a set unique_visitors to instantly identify distinct users. The dictionary user_profiles maps user IDs to names for quick lookup. Finally, we demonstrate that tuples are immutable by attempting to change a coordinate, which triggers a TypeError.

Common mistakes

  • Using lists for membership tests: Checking if an item exists in a large list (x in my_list) is slow (O(n)). Use a set instead for O(1) speed.
  • Modifying a list while iterating: This causes skipped elements or errors. Iterate over a copy (for x in my_list[:]) or build a new list.
  • Confusing empty dict and set: Remember that {} is an empty dictionary. Use set() to initialize an empty set.
  • Assuming order in dicts/sets: While dicts preserve insertion order in modern Python, sets do not guarantee any specific order. Do not rely on set indexing.

When to use it

StructureBest ForKey Characteristic
ListOrdered sequences, stacks, queuesMutable, allows duplicates
TupleFixed records, function returns, dict keysImmutable, hashable
DictLookups by name/ID, JSON-like dataKey-value pairs, fast access
SetUniqueness, mathematical operationsNo duplicates, fast membership

Practice

Guided Exercise: Create a list of numbers [1, 2, 2, 3, 4, 4, 5]. Convert it to a set to remove duplicates, then back to a sorted list. Print the result.
Challenge: Given a dictionary {"a": 1, "b": 2}, write code to swap the keys and values so that the output is {1: "a", 2: "b"}. Hint: Use a dictionary comprehension.

Quick check

Question: Which data structure would you choose to store a collection of email addresses where you need to quickly check if an address has already been processed?
Answer: A set, because it ensures uniqueness and provides very fast membership testing compared to a list.

Summary

Mastering lists, tuples, dictionaries, and sets allows you to choose the right tool for data storage and retrieval. By leveraging their specific properties—such as the immutability of tuples or the uniqueness of sets—you can write cleaner, faster, and more robust data analysis scripts.

Want to go beyond the notes?

Join CodingNow 2.0's Data Analytics course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Python Data Structures – FAQs

Quick answers about learning Python Data Structures in Data Analytics.

This free note from CodingNow 2.0 explains Python Data Structures in Data Analytics — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Data Analytics topic on CodingNow 2.0, including Python Data Structures, is 100% free with no signup required.
With focused practice, most students grasp Python Data Structures in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now