Skip to main content
1:1 mock interviews with Sumit, scored on a real hiring rubric.Book a slot →

Python Lists, Tuples, Sets and Dictionaries: When to Use Each

A practical guide to Python's built-in collections: lists, tuples, sets and dictionaries. Learn their methods, time complexity, comprehensions, the collections module and how to choose the right one.

Sumit KumarUpdated Oct 11, 20264 min readPython
Python Lists, Tuples, Sets and Dictionaries: When to Use Each

Python has four built-in collection types that you'll use in almost every program: lists, tuples, sets and dictionaries. Picking the right one makes your code faster, safer and easier to read. This guide covers how each one works and when to reach for it.

The four collections at a glance#

Python collections compared: list, tuple, set and dictionary with their ordering, mutability and duplicate rules
ListTupleSetDict
Syntax[1, 2, 3](1, 2, 3){1, 2, 3}{"a": 1}
OrderedYesYesNoYes (insertion order, 3.7+)
MutableYesNoYesYes
DuplicatesAllowedAllowedNoKeys unique
Lookup byIndexIndexMembershipKey
x in cO(n)O(n)O(1)O(1) for keys

Lists: ordered, changeable sequences#

Python
scores = [72, 88, 95]

scores.append(60)          # [72, 88, 95, 60]
scores.insert(0, 100)      # [100, 72, 88, 95, 60]
scores.extend([55, 81])    # add many
scores.remove(72)          # remove first matching value
last = scores.pop()        # remove and return the last item
scores.sort()              # sort in place
top3 = sorted(scores, reverse=True)[:3]   # new sorted list

print(scores[0], scores[-1])   # first and last
print(scores[1:4])             # slice
print(len(scores), sum(scores), max(scores))
OperationTime
lst[i], append, pop()O(1)
insert(0, x), pop(0), remove(x), x in lstO(n)
sort()O(n log n)
Need a queue?

list.pop(0) shifts every element. For queues, use collections.deque, which adds and removes from both ends in O(1).

List comprehensions#

Python
squares = [n * n for n in range(10)]
evens = [n for n in range(20) if n % 2 == 0]
names = [s.strip().title() for s in ["  asha", "RAVI "]]   # ['Asha', 'Ravi']
matrix = [[r * c for c in range(3)] for r in range(3)]

The copy trap#

Python
a = [1, 2, 3]
b = a            # b points to the SAME list
b.append(4)
print(a)         # [1, 2, 3, 4]  ← surprise!

c = a.copy()     # or list(a) or a[:] for a shallow copy
grid = [[0] * 3 for _ in range(3)]   # correct 2D list
bad = [[0] * 3] * 3                  # 3 references to ONE row

Tuples: fixed records#

Tuples are like lists that can't change. Use them for fixed groups of values, like coordinates or database rows.

Python
point = (3, 4)
rgb = (255, 128, 0)
single = (42,)            # the comma makes it a tuple

x, y = point              # unpacking
a, b = b, a               # swap two variables with a tuple

def min_max(nums):
    return min(nums), max(nums)   # returns a tuple

low, high = min_max([4, 9, 1])

Because they're immutable, tuples can be dictionary keys and set members, and they're slightly faster and lighter than lists.

Python
from typing import NamedTuple

class Student(NamedTuple):
    name: str
    marks: int

s = Student("Asha", 91)
print(s.name, s.marks)    # readable fields, still a tuple

Sets: unique items and fast membership#

Python
tags = {"python", "dsa", "python"}   # {'python', 'dsa'}: duplicates removed
tags.add("web")
tags.discard("java")                  # no error if missing
print("dsa" in tags)                  # O(1) lookup

emails = ["a@x.com", "b@x.com", "a@x.com"]
unique = list(set(emails))            # remove duplicates (order not kept)
unique_ordered = list(dict.fromkeys(emails))   # remove duplicates, keep order

empty = set()                         # NOT {} (that's an empty dict)

Set operations#

Python
python_devs = {"Asha", "Ravi", "Meera"}
java_devs = {"Ravi", "Karan"}

print(python_devs | java_devs)   # union: everyone
print(python_devs & java_devs)   # intersection: {'Ravi'}
print(python_devs - java_devs)   # difference: {'Asha', 'Meera'}
print(python_devs ^ java_devs)   # symmetric difference

Dictionaries: key-value lookups#

Python
user = {"name": "Asha", "age": 21, "skills": ["python", "sql"]}

print(user["name"])                 # KeyError if missing
print(user.get("email", "n/a"))     # safe access with a default
user["email"] = "asha@example.com"  # add or update
user.update({"age": 22, "city": "Pune"})
del user["city"]

for key, value in user.items():
    print(key, value)

print(list(user.keys()), list(user.values()))

Dict comprehensions and counting#

Python
prices = {"apple": 120, "mango": 80, "kiwi": 150}
discounted = {k: v * 0.9 for k, v in prices.items() if v > 100}

text = "the quick brown fox jumps over the lazy dog the end"
counts = {}
for word in text.split():
    counts[word] = counts.get(word, 0) + 1
print(counts["the"])   # 3
Hashable keys

Dictionary keys and set members must be hashable: strings, numbers, tuples of hashables. Lists and dicts can't be keys because they can change.

The collections module#

Python
from collections import Counter, defaultdict, deque, OrderedDict

# Counter: counting made easy
words = text.split()
print(Counter(words).most_common(2))   # [('the', 3), ('quick', 1)]

# defaultdict: no KeyError for new keys
groups = defaultdict(list)
for name, dept in [("Asha", "eng"), ("Ravi", "eng"), ("Meera", "hr")]:
    groups[dept].append(name)
# {'eng': ['Asha', 'Ravi'], 'hr': ['Meera']}

# deque: fast queue and sliding windows
q = deque([1, 2, 3])
q.appendleft(0)
q.popleft()
recent = deque(maxlen=3)    # keeps only the last 3 items

deque and dictionaries are the building blocks of many DSA techniques; see the sliding window technique.

How to choose#

You need to…Use
Keep items in order and change themList
Store a fixed record or return several valuesTuple
Remove duplicates or check membership fastSet
Look things up by name or IDDict
Count occurrencesCounter
Group items by a keydefaultdict(list)
Add/remove at both endsdeque
Python
# Real-world speed difference
banned = ["spam", "scam", "fake", ...]   # list: each check is O(n)
banned = {"spam", "scam", "fake", ...}   # set: each check is O(1)
clean = [w for w in words if w not in banned]

Understanding why these operations are O(1) or O(n) is covered in Big O notation explained. Java developers can compare with the Java Collections Framework.

Key takeaways#

  • Lists are ordered and mutable; tuples are ordered and immutable.
  • Sets store unique items with O(1) membership checks; dicts map unique keys to values with O(1) lookup.
  • Comprehensions build lists, sets and dicts in one readable line.
  • Beware of aliasing: assigning a list doesn't copy it.
  • Use Counter, defaultdict and deque from collections for counting, grouping and queues.