NANDHOO.

Lists, Tuples, Sets & Dictionaries

Lists, Tuples, Sets & Dictionaries


Python provides four main built-in collection types: lists, tuples, sets, and dictionaries. Each has different characteristics and is suited for different tasks. Understanding when to use each one is a key Python skill.


Why This Chapter Matters


Real programs handle collections of data constantly — shopping carts, user lists, scores, settings. Choosing the right collection type makes code more correct, readable, and efficient.


Lists


A list is an ordered, mutable (changeable) collection that allows duplicate values.


Creating Lists


fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True, 3.14]
empty = []

Accessing Items (Indexing)


Lists are zero-indexed — the first item is at index 0.


fruits = ["apple", "banana", "cherry"]
print(fruits[0])    # apple
print(fruits[-1])   # cherry (negative index counts from end)

Slicing


Extract a portion of a list:


numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])   # [20, 30, 40]
print(numbers[:3])    # [10, 20, 30]
print(numbers[2:])    # [30, 40, 50]
print(numbers[::2])   # [10, 30, 50] (every 2nd item)
print(numbers[::-1])  # [50, 40, 30, 20, 10] (reversed)

Modifying Lists


fruits = ["apple", "banana", "cherry"]

fruits.append("orange") # add to end fruits.insert(1, "blueberry") # insert at index fruits[0] = "avocado" # update item fruits.remove("banana") # remove by value popped = fruits.pop() # remove and return last item popped_at = fruits.pop(0) # remove and return item at index del fruits[0] # delete item at index fruits.clear() # remove all items


Useful List Methods


numbers = [3, 1, 4, 1, 5, 9, 2, 6]

numbers.sort() # sort in place (ascending) numbers.sort(reverse=True) # sort descending sorted_copy = sorted(numbers) # returns new sorted list (original unchanged) numbers.reverse() # reverse in place print(numbers.count(1)) # count occurrences of a value print(numbers.index(5)) # index of first occurrence numbers2 = numbers.copy() # shallow copy combined = numbers + [10, 11] # concatenate


List Length


print(len(fruits))   # number of items

Checking Membership


if "apple" in fruits:
    print("Found it!")

Tuples


A tuple is an ordered, immutable (cannot be changed after creation) collection.


coordinates = (10.5, 20.3)
rgb = (255, 0, 128)
single = (42,)       # comma needed for single-item tuple
empty = ()

Why Use Tuples?


  • They signal that data should not change (coordinates, RGB, database rows)
  • They are slightly faster than lists
  • They can be used as dictionary keys (lists cannot)
  • Function return often uses tuples implicitly: return a, b

def get_min_max(numbers):
    return min(numbers), max(numbers)

low, high = get_min_max([3, 1, 9]) # tuple unpacking


Tuple Unpacking


point = (4, 7)
x, y = point
print(x, y)   # 4 7

a, *rest = (1, 2, 3, 4, 5) print(a) # 1 print(rest) # [2, 3, 4, 5]


Sets


A set is an unordered collection of unique values. Duplicates are automatically removed.


tags = {"python", "coding", "beginner"}
numbers = {1, 2, 3, 2, 1}
print(numbers)   # {1, 2, 3} — duplicates removed
empty_set = set()   # Note: {} creates an empty dict, not a set!

Set Operations


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

print(a | b) # {1, 2, 3, 4, 5, 6} union print(a & b) # {3, 4} intersection print(a - b) # {1, 2} difference print(a ^ b) # {1, 2, 5, 6} symmetric difference


Useful Set Methods


tags = {"python", "coding"}
tags.add("backend")
tags.discard("cooking")   # no error if not found
print("python" in tags)   # True (fast membership check)

Sets have O(1) average-time membership testing — much faster than lists for large datasets.


Dictionaries


A dictionary stores key-value pairs. Keys must be unique and hashable.


Creating Dictionaries


student = {
    "name": "Sam",
    "grade": 11,
    "courses": ["Math", "Physics"]
}

Accessing Values


print(student["name"])                # Sam
print(student.get("age"))             # None (no KeyError)
print(student.get("age", "Unknown"))  # Unknown (default value)

Use .get() when the key might not exist to avoid KeyError.


Modifying Dictionaries


student["name"] = "Sam Rao"      # update value
student["email"] = "s@email.com" # add new key
del student["grade"]             # delete a key
student.pop("courses", None)     # remove and return value
student.update({"city": "Mumbai", "age": 17})  # merge dict

Iterating Over a Dictionary


person = {"name": "Leo", "age": 16, "city": "Delhi"}

for key in person: print(key)


for key, value in person.items(): print(f"{key}: {value}")


print(list(person.keys())) print(list(person.values()))


Checking Keys


if "name" in student:
    print("Has a name")

Dictionary Comprehension Preview


squares = {n: n**2 for n in range(1, 6)}
print(squares)   # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Choosing the Right Collection


TypeOrderedMutableDuplicatesWhen to Use
listYesYesYesGeneral ordered collections
tupleYesNoYesFixed data, function returns, dict keys
setNoYesNoUnique values, fast membership tests
dictYes (3.7+)YesKeys: NoKey-value lookups, structured data

Nested Collections


Collections can contain other collections:


students = [
    {"name": "Asha", "score": 95},
    {"name": "Leo", "score": 88},
    {"name": "Mina", "score": 92}
]

for student in students: print(student["name"], student["score"])


Common Mistakes


  • using {} for an empty set (creates a dict instead — use set())
  • calling .remove() on a value not in the list (raises ValueError — use .discard() for sets)
  • accessing a dictionary key that does not exist (use .get() or check with in)
  • modifying a list while iterating over it
  • expecting a set to be ordered (it is not)

Mini Exercises


  1. Create a list of numbers and find the smallest, largest, and total sum without using min/max/sum built-ins.
  2. Remove all duplicate values from a list using a set.
  3. Create a dictionary of countries and their capitals. Print each pair formatted nicely.
  4. Write a function that takes a list and returns a tuple with (min, max, average).
  5. Given two sets, find the values that are in one set but NOT the other.

Review Questions


  1. What is the key difference between a list and a tuple?
  2. Why can't you have duplicate keys in a dictionary?
  3. When is a set a better choice than a list?
  4. What does dict.get("key", default) do differently from dict["key"]?
  5. How do you iterate over both keys and values of a dictionary simultaneously?

Reference Checklist


  • I can create and modify lists using all common methods
  • I understand slicing syntax for lists
  • I know why and when to use tuples
  • I understand set operations (union, intersection, difference)
  • I can create, access, modify, and iterate dictionaries
  • I know how to choose the right collection for a task