FAQ Part 6: Lists, Tuples, and Dictionaries

What is the difference between lists and tuples?

Lists are mutable ([1, 2]), tuples are immutable ((1, 2)).

How do I create a dictionary?

person = {"name": "Alice", "age": 25}

How do I loop through dictionary items?

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

How do I create a list with repeating elements?

zeros = [0] * 5    # [0, 0, 0, 0, 0]

How do I copy a list properly?

copy1 = original[:]           # Slice
copy2 = original.copy()       # Method
copy3 = list(original)        # Constructor

⚠️ Avoid using copy = original — it creates a reference, not a new list.

How do I remove duplicates from a list?

unique = list(set(my_list))

Note: This does not preserve order.

What is list comprehension and why is it useful?

A concise way to create lists:

squares = [x*x for x in range(10)]

When should I use a tuple instead of a list?

  • Use tuples for fixed data.
  • Tuples are immutable and slightly faster than lists.

Can a tuple contain mutable elements?

Yes. Tuples can hold lists or dictionaries:

t = ([1, 2], [3, 4])
t[0][0] = 100  # Allowed

How do I create a single-element tuple?

t = (42,)  # The comma is required

Can I unpack a tuple into variables?

a, b, c = (1, 2, 3)

How do I safely access a value in a dictionary?

value = my_dict.get("key", "default_value")

How do I loop through keys and values?

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

Can dictionary keys be of any type?

Keys must be immutable types like strings, numbers, or tuples. Lists and dicts can’t be keys.

How do I remove a key from a dictionary?

del my_dict["key"]
removed = my_dict.pop("key", "default")