Ch 10 covers two important data structures: tuples (immutable ordered sequences) and dictionaries (mutable key-value mappings). Understanding when to use each is essential for writing efficient Python code.
Creation: t = (1, 2, 3), single = (5,) — comma required! Without comma: (5) is just integer 5. Empty: t = (). From other types: tuple([1,2,3]), tuple("hello"). Immutable: t[0] = 10 → TypeError. Operations: indexing, slicing, concatenation (+), repetition (*), membership (in), len(), count(), index(). Packing: t = 1, 2, 3. Unpacking: a, b, c = t. Swap: a, b = b, a. Use cases: fixed data (coordinates, RGB), dictionary keys, function return values, data integrity.
Creation: d = {"name": "Alice", "age": 14}. Access: d["name"] or d.get("name", "default"). Keys must be immutable (str, int, tuple — NOT list). Values: any type. Add/update: d["city"] = "Delhi". Delete: del d["age"], d.pop("age"), d.clear(). Methods: keys(), values(), items() (key-value tuples), update(dict2), setdefault(key, default). Iterate: for k in d (keys), for k,v in d.items(). Nested dict: students = {"s1": {"name":"Alice", "marks": 95}}. Dictionary comprehension: {x: x**2 for x in range(5)}.
Download: https://ncert.nic.in/textbook/pdf/kecs110.pdf | Complete Book: https://ncert.nic.in/textbook/pdf/kecs1ps.zip
Use a tuple when: (1) Data should not change — coordinates (x,y), database records, configuration constants. (2) Using as dictionary key or set element (must be hashable/immutable). (3) Returning multiple values from a function. (4) Slightly better performance (tuples use less memory). Use a list when: (1) Data needs to be modified — adding, removing, reordering items. (2) Building a collection dynamically. (3) Using list methods (sort, append, extend). Rule of thumb: if the collection is fixed and shouldn't change, use a tuple. If it's dynamic, use a list.
Book a Trial + Diagnostic session. Get a personalized Learning Path with clear milestones, tutor match, and a plan recommendation — all within 24 hours.
Book Trial + Diagnostic →