Skip to main content
A data structure is a way of organising and storing data so it can be accessed, updated, and processed efficiently. Python ships with several powerful built-in data structures — each designed for a different use case. Understanding them deeply will help you write programs that are faster, more readable, and easier to maintain. This page covers all the essential ones: strings, lists, tuples, sets, dictionaries, and deques.

Overview

Strings

A string (str) is an immutable sequence of Unicode characters used to store text. You can create strings with single quotes, double quotes, or triple quotes for multiline content.

Indexing and Slicing

Access individual characters by position, or extract a substring using start:stop:step:

String Operators

Common String Methods

Splitting and Joining

f-Strings

Use f-strings for readable string interpolation:
Strings are immutable — you cannot change a character in place. To “modify” a string, create a new one: text = "J" + text[1:].

Lists

A list is an ordered, mutable collection that can hold elements of different data types. It is the most versatile and commonly used data structure in Python.

Accessing Elements

Lists support indexing and slicing just like strings:

Common List Methods

List Comprehension

Comprehensions provide a concise, Pythonic way to build lists:

Tuples

A tuple is an ordered, immutable collection. Once created, it cannot be changed, making it ideal for data that should remain constant.
A single-element tuple must include a trailing comma: (10,). Without it, (10) is just an integer in parentheses.

Accessing Elements

Tuples support the same indexing and slicing as lists:

Tuple Packing and Unpacking

Sets

A set is an unordered, mutable collection of unique elements. Duplicates are removed automatically, making sets perfect for membership testing and eliminating redundancy.
Use set() to create an empty set. Using {} creates an empty dictionary, not a set.

Common Set Methods

Set Operations

Dictionaries

A dictionary (dict) stores data as key-value pairs. Keys must be unique and immutable; values can be any type. Dictionaries preserve insertion order in Python 3.7+.

Accessing Values

Adding, Updating, and Removing

Iterating a Dictionary

Dictionary Comprehension

deque

A deque (double-ended queue) from Python’s collections module supports fast O(1) insertion and deletion from both ends — far more efficient than a list for queue-like operations.

Rotating a deque

Prefer deque over list when you frequently add or remove elements from the beginning of a collection. A list.insert(0, x) is O(n); deque.appendleft(x) is O(1).