Data Structures

Python Data Structures Overview

SI
DS
Description
Usage Scenario
Pros
Cons

1

List []

Ordered, mutable, allows duplicates.

Storing and modifying a sequence of items.

1. Dynamic sizing 2. Built-in methods 3. Easy indexing

1. Slower for search operations

2

Tuple ()

Ordered, immutable, allows duplicates.

Returning multiple values from a function.

1. Memory-efficient 2. Safe from unintended changes

1. Cannot modify contents

3

Set {} / set()

Unordered, mutable, no duplicates.

Membership testing, removing duplicates.

1. Fast lookup 2. Ensures uniqueness

1. No indexing

4

Dictionary {key: val}

Key-value pairs, unordered in <3.6, ordered from 3.7+.

Lookups by key, JSON-like data.

1. Fast key access 2. Flexible structure

1. Keys must be hashable

5

Stack [list]

LIFO, often implemented using lists.

Undo functionality, parsing.

1. Simple to implement with lists 2. Built-in methods like append, pop

1. Manual enforcement of LIFO

6

Queue deque([])

FIFO, implemented using collections.deque.

Scheduling tasks, producer-consumer.

1. Fast appends and pops from both ends

1. Not built-in as list

7

namedtuple namedtuple()

Immutable object with named fields.

Replacing simple classes.

1. Improves readability 2. Lightweight and immutable

1. Cannot modify fields

8

Counter Counter()

Dict subclass for counting hashable items.

Word frequency, histogram data.

1. Fast frequency count 2. Built-in operations like most_common()

1. Not suitable for unhashables

9

defaultdict defaultdict()

Dict subclass with a default factory for missing keys.

Grouping values, building indexes.

1. Avoids KeyError 2. Cleaner code

1. Slight overhead due to factory


Code sample

my_list = [1, 2, 3]
my_list.append(4)
print(my_list)  # [1, 2, 3, 4]
from collections import namedtuple

Point = namedtuple("Point", "x y")
pt = Point(1, 2)
print(pt.x, pt.y)  # 1 2

Last updated