Guide Python Beginner

5.4 Sequence Data Types

Python's four sequence types — str, list, tuple, and range — their mutability differences, typical uses, and the shared operations that work across all of them.

2 min read

A sequence is an ordered collection accessible by integer index. All four types below share this trait but differ in mutability and typical use.

str

An immutable sequence of Unicode characters — covered in exhaustive depth in Chapter 9: Strings.

>>> type("hi")
<class 'str'>

list

What Is It?

A MUTABLE, ordered, resizable sequence — Python’s general-purpose “array”.

Why Is It Used?

It’s the default choice for any ordered collection you’ll add to, remove from, or reorder — covered in exhaustive depth in Chapter 10: Lists.

>>> l = [1, 2, 3]
>>> l.append(4)
>>> l
[1, 2, 3, 4]

tuple

What Is It?

An IMMUTABLE, ordered sequence.

Why Is It Used?

It represents a fixed-size, fixed-content record (like a coordinate pair) and can be used as a dict key or set member, unlike a list — covered in exhaustive depth in Chapter 11: Tuples.

>>> t = (1, 2, 3)
>>> t[0]
1
>>> t[0] = 99
Traceback (most recent call last):
TypeError: 'tuple' object does not support item assignment

range

What Is It?

A memory-efficient, immutable sequence of numbers, generated lazily rather than stored all at once.

Why Is It Used?

Iterating a range(1000000) uses almost no memory, unlike building an actual list of a million numbers.

>>> type(range(5))
<class 'range'>
>>> list(range(5))
[0, 1, 2, 3, 4]

Common Operations

Indexing and len() work identically across all sequence types, since they all implement the same sequence protocol:

>>> s, l, t = "hello", [1, 2, 3], (1, 2, 3)
>>> s[0], l[0], t[0]
('h', 1, 1)
>>> len(s), len(l), len(t)
(5, 3, 3)

Quick Interview Answer

“Python has four sequence types sharing the same indexing/len() protocol: str (immutable text), list (mutable, resizable — the general-purpose array), tuple (immutable, fixed-content — usable as a dict key or set member, unlike a list), and range (a lazy, memory-efficient sequence of numbers that never materializes the full list).”

Common Mistakes

  • Trying to mutate a tuple in place (t[0] = 99) instead of recognizing it’s immutable and building a new tuple.
  • Materializing a huge range() into a list() unnecessarily, losing its lazy memory efficiency for no reason.
  • Using a list as a dict key or set member and hitting TypeError: unhashable type: 'list' — reach for a tuple instead.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form