EasyConcept

What is the difference between a list and a tuple in Python?

Technology:
Python
Experience:
Intern,
Junior

Quick answer

A list is mutable and can be changed after creation, while a tuple is immutable; tuples are slightly faster, use less memory and can be used as dictionary keys when their items are hashable.

Detailed explanation

Use a list for a collection that grows, shrinks or is reordered, such as the items in a shopping cart. Use a tuple for a fixed group of values that belong together, such as a coordinate (x, y) or a database row. Tuples also signal to the reader that the data should not change.

Immutability applies to the tuple itself: if a tuple contains a list, that list can still be modified. A one-item tuple needs a trailing comma, (5,), because (5) is just the number 5 in parentheses.

Example

python
items = [1, 2, 3]
items.append(4)          # fine

point = (10, 20)
point[0] = 5             # TypeError: 'tuple' object does not support item assignment

locations = {(10, 20): "home"}   # tuples can be dict keys
  • PythonEasy

    What are *args and **kwargs in Python?

    *args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary, which lets a function accept a variable number of arguments.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    Why should you not use a mutable default argument in Python?

    Default argument values are evaluated once when the function is defined, so a default list or dictionary is shared between every call that does not pass its own, causing data to leak between calls.

    Junior 路 Mid-level 路 Functions & Scope
  • PythonMedium

    What is the difference between @staticmethod and @classmethod in Python?

    A classmethod receives the class as its first argument (cls) and can create or configure instances, while a staticmethod receives no automatic argument and is just a function placed inside the class namespace.

    Junior 路 Mid-level 路 Object-Oriented Programming
  • PythonMedium

    What are decorators in Python and how do they work?

    A decorator is a function that takes another function and returns a modified version of it, letting you add behaviour such as logging, caching or access control without changing the original code.

    Mid-level 路 Senior 路 Functions & Scope