[{"data":1,"prerenderedAt":70},["ShallowReactive",2],{"qa-\u002Fpython\u002Fdata-structures\u002Ftuples":3},{"page":4,"siblings":52,"blog":43},{"id":5,"title":6,"body":7,"description":11,"difficulty":14,"extension":15,"framework":16,"frameworkSlug":17,"meta":18,"navigation":19,"order":12,"path":20,"questions":21,"related":43,"seo":44,"seoDescription":45,"stem":46,"subtopic":47,"topic":48,"topicSlug":49,"updated":50,"__hash__":51},"qa\u002Fpython\u002Fdata-structures\u002Ftuples.md","Tuples",{"type":8,"value":9,"toc":10},"minimark",[],{"title":11,"searchDepth":12,"depth":12,"links":13},"",2,[],"medium","md","Python","python",{},true,"\u002Fpython\u002Fdata-structures\u002Ftuples",[22,27,31,35,39],{"id":23,"difficulty":24,"q":25,"a":26},"tuple-vs-list","easy","What is the difference between a tuple and a list, and when should you use each?","A **`list`** is **mutable** and variable-length — use it for a **homogeneous,\nchanging** collection you add to, remove from, or reorder. A **`tuple`** is\n**immutable** and fixed — use it for a **heterogeneous, fixed record** whose\nshape won't change, like a coordinate or a database row.\n\n```python\nscores = [90, 85, 70]   # changing collection -> list\nscores.append(60)       # fine\n\npoint = (3, 4)          # fixed record -> tuple\npoint[0] = 9            # TypeError — tuples are immutable\n```\n\nTuples are also slightly **faster and more memory-efficient**, and because\nthey're **hashable** they can serve as dict keys or set members (a list can't).\nRule of thumb: reach for a tuple when the data is a fixed bundle that shouldn't\nchange, and a list when you need to mutate the collection.\n",{"id":28,"difficulty":24,"q":29,"a":30},"packing-unpacking","What are tuple packing and unpacking, and how do you write a single-element tuple?","**Packing** collects several values into one tuple — the parentheses are often\noptional. **Unpacking** spreads a tuple's items into separate names in one\nassignment, which is how you return and receive multiple values cleanly.\n\n```python\nt = 1, 2, 3          # packing (parentheses optional)\na, b, c = t          # unpacking -> a=1, b=2, c=3\nfirst, *rest = t     # extended unpacking -> first=1, rest=[2, 3]\n\none = (5)            # NOT a tuple — just int 5 in parentheses\none = (5,)           # a 1-element tuple — the trailing comma makes it\n```\n\nThe key gotcha is the **single-element tuple**: it's the **trailing comma**, not\nthe parentheses, that creates a tuple — `(5)` is just the integer `5`, while\n`(5,)` is a one-tuple. When in doubt, the comma is what defines a tuple.\n",{"id":32,"difficulty":14,"q":33,"a":34},"shallow-immutability","Is a tuple's immutability deep? Can a tuple contain mutable objects?","A tuple's **immutability is shallow**. You can't reassign or resize its slots,\nbut each slot just holds a **reference** — and if that reference points to a\nmutable object (like a list), that object can still be changed in place.\n\n```python\nt = (1, [2, 3])\nt[1].append(4)     # allowed — mutating the list inside the tuple\nprint(t)           # (1, [2, 3, 4])\n\nt[1] = [9]         # TypeError — can't reassign a tuple slot\n```\n\nA consequence interviewers love: a tuple that contains a list is **not\nhashable**, because hashability requires every element to be immutable too —\nso `hash((1, [2]))` raises `TypeError`. Bottom line: the tuple's structure is\nfrozen, but the objects it points to may not be.\n",{"id":36,"difficulty":14,"q":37,"a":38},"namedtuple","What is a namedtuple and how does collections.namedtuple compare to typing.NamedTuple?","A **namedtuple** is an **immutable** tuple subclass with **named fields** —\ngiving you readable, hashable, lightweight records that still behave like\ntuples (index access, unpacking, comparison). There are two ways to define one.\n\n```python\nfrom collections import namedtuple\nPoint = namedtuple(\"Point\", [\"x\", \"y\"])\np = Point(3, 4)\np.x, p[0]        # 3, 3  — named AND index access\np.x = 9          # AttributeError — immutable\n\nfrom typing import NamedTuple\nclass Point(NamedTuple):     # class syntax with type hints + defaults\n    x: int\n    y: int = 0\n```\n\nThe `collections` form is concise; the `typing.NamedTuple` class form adds\n**type annotations, defaults, and the ability to add methods**. Use a namedtuple\nfor small fixed records when you want clarity over a bare tuple; reach for a\n`@dataclass` when you need mutability or richer behavior.\n",{"id":40,"difficulty":14,"q":41,"a":42},"tuple-dict-key","Why can a tuple be used as a dictionary key when a list cannot?","Dict keys and set members must be **hashable**, which in practice means\n**immutable** with a stable hash for the object's lifetime. A tuple of immutable\nvalues is hashable, so it works as a key; a list is mutable and **unhashable**,\nso it doesn't.\n\n```python\ngrid = {}\ngrid[(0, 0)] = \"origin\"   # tuple key — works\ngrid[(1, 2)] = \"point\"\n\ngrid[[3, 4]] = \"x\"        # TypeError: unhashable type: 'list'\n```\n\nThis makes tuples ideal for **composite \u002F multi-part keys** — like `(row, col)`\ncoordinates or `(lat, lon)` pairs. The one caveat: a tuple is only hashable if\n**all its contents are** too, so `(1, [2])` still fails. Use an immutable tuple\nwhenever you need a multi-value key.\n",null,{"description":11},"Python interview questions on tuples vs lists, packing and unpacking, single-element tuples, shallow immutability, namedtuples, and tuples as dict keys.","python\u002Fdata-structures\u002Ftuples","Tuples & Named Tuples","Data Structures","data-structures","2026-06-18","k8gJCQHd3O516LEW4hNwzbc-dMsxspsIWpQ8XWKiCig",[53,57,58,62,66],{"subtopic":54,"path":55,"order":56},"Lists & Slicing","\u002Fpython\u002Fdata-structures\u002Flists",1,{"subtopic":47,"path":20,"order":12},{"subtopic":59,"path":60,"order":61},"Dictionaries","\u002Fpython\u002Fdata-structures\u002Fdictionaries",3,{"subtopic":63,"path":64,"order":65},"Sets & Frozensets","\u002Fpython\u002Fdata-structures\u002Fsets",4,{"subtopic":67,"path":68,"order":69},"The collections Module","\u002Fpython\u002Fdata-structures\u002Fcollections-module",5,1781808679453]