Both lists and tuples are ordered sequences that can hold items of any type, support indexing and slicing, and can be iterated. The main difference is that lists are mutable and tuples are immutable. List - Created with square brackets: fruits = ['apple', 'banana', 'mango'] - Mutable: you can add, remove and change items. fruits.append('grape') fruits[0] = 'orange' fruits.remove('banana') fruits.sort() - Many methods: append, extend, insert, remove, pop, sort, reverse, clear, index, count. - Use for collections that change over time: items in a cart, results being built in a loop. Tuple - Created with parentheses (or just commas): point = (10, 20) - A single-item tuple needs a trailing comma: single = (5,) — (5) is just the number 5. - Immutable: you cannot add, remove or reassign items. point[0] = 15 # TypeError: 'tuple' object does not support item assignment - Only two methods: count and index. - Use for fixed collections of related values: coordinates, RGB colours, database rows, function return values. def min_max(values): return min(values), max(values) # returns a tuple low, high = min_max([4, 9, 1]) # tuple unpacking Key differences - Mutability: list mutable; tuple immutable. - Syntax: [ ] vs ( ). - Hashability: tuples can be dictionary keys and set elements if all their items are hashable; lists cannot (they are unhashable because they are mutable). locations = {(18.52, 73.85): 'Pune'} # valid - Performance: tuples are slightly faster to create and iterate and use less memory, because their size is fixed (Python can also cache and reuse small constant tuples). - Intent: a tuple signals "this data should not change", which makes code safer and clearer; a list signals a collection that may grow or change. - Methods: lists have many modification methods; tuples have only count and index. Important nuance: shallow immutability A tuple's references cannot change, but if it contains a mutable object, that object can still change: t = ([1, 2], 3) t[0].append(4) # allowed: t is now ([1, 2, 4], 3) Such a tuple is also not hashable. Converting between them list((1, 2, 3)) # [1, 2, 3] tuple([1, 2, 3]) # (1, 2, 3) Named tuples For readable fixed records, use collections.namedtuple or typing.NamedTuple: from typing import NamedTuple class Point(NamedTuple): x: float y: float p = Point(1.5, 2.0) print(p.x) Dataclasses with frozen=True are another option for immutable records with more features. Interview summary: "Lists are mutable, use square brackets and have many modification methods — good for changing collections. Tuples are immutable, use parentheses, are slightly faster and lighter, and can be used as dictionary keys — good for fixed records and multiple return values."
Ravindra Wadile · · 0 likes