Lists, Tuples & Dictionaries in Python

9 min read PYTHON 2 views

Lists, Tuples & Dictionaries in Python

Real programs rarely work with one standalone string or number at a time—they store collections of records, user profiles, settings, and search results. Python builds four versatile data structures directly into the language core: Lists, Tuples, Sets, and Dictionaries.

1. Python Lists (Ordered, Mutable Sequences)

A list holds an ordered sequence of items inside square brackets [ ]. Lists allow duplicate items and can be modified after creation by adding, removing, or sorting elements:

skills = ["HTML", "CSS", "Python"]
skills.append("SQL")          # Add to end
skills.insert(2, "JavaScript")
first = skills[0]             # Zero-based indexing -> "HTML"
last = skills[-1]             # Negative index counts from end -> "SQL"
subset = skills[1:3]          # Slicing -> ["CSS", "JavaScript"]
print(skills, subset)
  • append(item) adds a single item to the end in O(1) amortized time.
  • pop() removes and returns the last element (or element at index).
  • len(skills) counts total elements; "Python" in skills tests membership.

2. Tuples (Ordered, Immutable Records)

A tuple uses parentheses ( ) instead of square brackets. Once created, elements inside a tuple cannot be appended, swapped, or deleted. Choose tuples for fixed structured coordinates, RGB colors, or database rows that should stay protected from accidental mutation:

dimensions = (1920, 1080)
width, height = dimensions    # Clean tuple unpacking
print(f"Resolution: {width}x{height}")

3. Dictionaries (Fast Key-Value Lookup Tables)

A dictionary (dict) stores pairs of unique immutable keys mapped to values inside curly braces { }. Looking up a value by key stays near instantaneous regardless of whether the dictionary has ten keys or one million:

course = {
    "slug": "python-for-beginners",
    "title": "Python for Beginners",
    "lessons": 6,
    "is_free": True
}

# Safe lookup with .get() avoids KeyError on missing keys
level = course.get("level", "Beginner")
print(course["title"], "| Level:", level)

# Iterating keys and values together
for key, value in course.items():
    print(f"{key}: {value}")

4. Comparing Core Python Collections

Collection Syntax Mutable? Primary Use Case
list [1, 2, 3] Yes Ordered lists that grow, filter, or sort dynamically.
tuple (1, 2, 3) No Fixed data records and returning multiple values from functions.
set {1, 2, 3} Yes Deduplicating tags and testing membership cleanly.
dict {"a": 1} Yes JSON-like records, configurations, frequency counters.

5. Sets (Unique Collections) & Nested Data Structures

When deduplicating student tags, email lists, or search keywords, a set eliminates duplicates automatically and computes unions (a | b), intersections (a & b), and differences (a - b) rapidly:

web_tags = {"html", "css", "js"}
backend_tags = {"python", "sql", "js"}

print("Shared skill:", web_tags & backend_tags)   # {'js'}
print("All unique tags:", web_tags | backend_tags)

# Dictionary comprehension to double passing scores quickly
raw_marks = {"Riya": 80, "Kabir": 45, "Sam": 92}
passed = {name: mark for name, mark in raw_marks.items() if mark >= 50}
print(passed)

6. Avoid Aliasing Bugs When Copying Lists or Dictionaries

Writing copy_list = original_list does not duplicate the items—it creates two variable names pointing to the exact same list object in memory. Mutating copy_list modifies original_list silently! To modify a separate copy safely, call original_list.copy() or slice original_list[:] (or copy.deepcopy() when nested lists/dictionaries live inside).

7. Practice Exercise & Key Takeaways

Extend the Python code runner snippet below by storing a list of three student dictionaries (name, course, score), looping through them to print only learners scoring 80 or higher, and tracking unique enrolled tracks inside a set().

  • Match data structure to access pattern: Choose list when sequence order and duplicates matter, tuple for fixed read-only records, set for fast deduplication and membership checks, and dict when looking up attributes by named identifier.
  • Guard missing dictionary keys cleanly: Calling record.get("key", fallback) avoids unhandled KeyError exceptions on incomplete JSON API payloads or optional configuration fields.
  • Avoid unintended shared references: Explicitly copy lists or dictionaries via .copy() before modifying them inside helper functions unless caller mutation is clearly documented.
python Example
Run Code
# Lists store ordered collections
topics = ["Variables", "Loops", "Functions"]
topics.append("Modules")
print("First topic:", topics[0], "| Last:", topics[-1])

# Dictionaries map unique keys to structured values
student = {
    "name": "Rohan",
    "track": "Python",
    "completed": 5
}
student["completed"] += 1
print(f"{student['name']} completed {student.get('completed')} lessons.")

Related Tutorials