Sobes.tech
Junior — Middle

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

sobes.tech AI

Answer from AI

In Python, the term "sequence" is a general data type that supports ordered access to elements by index and usually supports slicing operations. Sequences can be mutable and immutable.

A list is a specific type of sequence that is mutable. It allows adding, removing, and modifying elements.

Main differences:

  • Sequence is an abstract data type (interface) that includes lists, tuples, strings, and other types supporting ordered access.
  • List is a concrete implementation of a sequence that is mutable.

Example:

seq = (1, 2, 3)  # tuple — immutable sequence
lst = [1, 2, 3]  # list — mutable sequence

lst.append(4)  # allowed
# seq.append(4)  # will cause an error because tuple is immutable

Thus, a list is a mutable sequence, and a sequence is a broader concept that includes different types with ordered access.