Sobes.tech
Junior — Middle

What are the differences between lists and tuples in Python?

sobes.tech AI

Answer from AI

Main differences between lists and tuples in Python:

  • Mutability: Lists are mutable, meaning you can add, remove, and modify elements after creation. Tuples are immutable, their contents cannot be changed.
  • Syntax: Lists are created using square brackets [], while tuples are created using parentheses () or without brackets if elements are comma-separated.
  • Usage: Tuples are often used to store fixed sets of data, such as coordinates, and can be used as keys in dictionaries (if they contain hashable elements), whereas lists are used for dynamic collections.

Example:

my_list = [1, 2, 3]
my_list[0] = 10  # allowed

my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # will raise a TypeError