Python Mastery – From Basics to Brilliance / Type Hints and Code Quality

List, Dict, Tuple Type Hint

📋 List, Dict & Tuple Type Hints

Type hints can also specify what types of values a collection should contain.


1️⃣ List Type Hint

Use list[type] to specify the type of elements in a list.

names: list[str] = ["Tisha", "Rahul", "Anu"]

Another example:

marks: list[int] = [80, 90, 75]

2️⃣ Dict Type Hint

Use dict[key_type, value_type].

student: dict[str, int] = {
    "Math": 90,
    "English": 85
}

Example:

students: dict[str, int] = {
    "Tisha": 23,
    "Rahul": 21
}

3️⃣ Tuple Type Hint

Use tuple[type, ...] when all elements have the same type.

numbers: tuple[int, ...] = (1, 2, 3, 4)

If the tuple has specific types in specific positions:

student: tuple[str, int] = ("Tisha", 23)

Here:

1st value → str
2nd value → int

⚖️ Quick Summary

Type Hint

Meaning

Example

list[str]

List of strings

["A", "B"]

list[int]

List of integers

[1, 2, 3]

dict[str, int]

String keys, integer values

{"Age": 23}

tuple[int, ...]

Tuple of integers

(1, 2, 3)

tuple[str, int]

String followed by integer

("Tisha", 23)

⭐ Remember

list[type]           → List elements
dict[key, value]     → Key + Value types
tuple[type, ...]     → Same type
tuple[type1, type2]  → Specific types by position