📚 Tuples and Dictionaries in Python

1. Tuples (tuple)

A tuple is an ordered sequence of items enclosed in parentheses ( ). Tuples are immutable. They are faster than lists and protect data from accidental modification.

Creating a Single Element Tuple

To create a tuple with only one element, you must include a comma after the element, otherwise Python treats it as a standard expression in parentheses.

Correct: t = (10,) | Incorrect: t = (10)

Tuple Operations: Indexing, slicing, concatenation, repetition, len(), max(), min(), sum(), count(), index(). (Tuples do NOT have append(), remove(), or sort() methods because they are immutable).

2. Dictionaries (dict)

A dictionary is an unordered collection of key-value pairs, enclosed in curly braces { }. Dictionaries are mutable.

D = {"name": "Aman", "age": 16, "marks": 95}

Rules for Keys: Keys must be unique and must be of an immutable data type (like string, number, or tuple). Values can be of any type and can be duplicated.

3. Dictionary Operations and Methods

Accessing and Modifying

Access value: val = D["name"] or val = D.get("name")

Update/Add: D["age"] = 17 (Updates if key exists, adds new pair if it doesn't).

Common Methods

keys(): Returns a list-like object of all keys.

values(): Returns a list-like object of all values.

items(): Returns a list-like object of (key, value) tuples.

pop(key): Removes the key-value pair and returns the value.

clear(): Removes all items from the dictionary.