Fundamentals 9 min read

Python Data Structures: Strings, Lists, Tuples, Dicts, Sets, Stacks & Queues

This article introduces essential Python data structures—including strings, lists, tuples, dictionaries, sets, as well as stack and queue implementations—explaining their characteristics, usage, and providing clear code examples to illustrate creation, indexing, slicing, and common operations.

Model Perspective
Model Perspective
Model Perspective
Python Data Structures: Strings, Lists, Tuples, Dicts, Sets, Stacks & Queues

Data Structures in Algorithms

Algorithms require appropriate in‑memory data structures to store temporary data during execution; choosing the right structure is crucial for efficiency.

Python Data Structures

String: ordered, immutable sequence of elements

List: ordered, mutable sequence

Tuple: ordered, immutable sequence

Dictionary: unordered collection of key‑value pairs

Set: unordered collection of unique elements

String

A string is an ordered, immutable sequence representing textual data.

<code># generate a string
astring = "hello 2023!"  # single or double quotes
# positive indexing (first index is 0)
astring[0]  # 'h'
astring[2]  # 'l'
# negative indexing (last element is -1)
astring[-1]  # '!'
# slicing (start inclusive, end exclusive)
astring[2:4]  # 'll'
</code>

List

In Python, a list stores a mutable sequence of elements, which can be of different types.

<code># generate a list
alist = [1, 2, True, 'Hello world', [1, 2, 3]]
# positive indexing
alist[0]  # 1
alist[2]  # True
# negative indexing
alist[-1]  # [1, 2, 3]
# slicing
alist[2:4]  # [True, 'Hello world']
</code>

Tuple

A tuple is an immutable (read‑only) sequence, similar to a list but cannot be modified after creation.

<code># generate a tuple
atuple = (1, 2, True, 'Hello world', [1, 2, 3])
# positive indexing
atuple[0]  # 1
atuple[2]  # True
# negative indexing
atuple[-1]  # [1, 2, 3]
# slicing
atuple[2:4]  # [True, 'Hello world']
</code>

List elements can be added, removed, or changed, which is not possible for tuples.

<code>>> alist[0] = 3  # modify first element
>>> alist[0]
3
>>> atuple[0] = 3  # raises TypeError
TypeError: 'tuple' object does not support item assignment
</code>

Dictionary

A dictionary stores data as key‑value pairs; the colon (:) separates keys from values.

<code># generate a dictionary
adict = {
  "manual_color": "Yellow",
  "approved_color": "Green",
  "refused_color": "Red"
}
# access values by key
adict['manual_color']  # 'Yellow'
adict.keys()   # dict_keys(['manual_color', 'approved_color', 'refused_color'])
adict.values() # dict_values(['Yellow', 'Green', 'Red'])
</code>

Set

A set contains unordered, unique elements.

<code># generate a set
aset = {1, 2, 2, 3, 'hello', (1, 2)}
# duplicate elements are removed
aset  # {(1, 2), 1, 2, 3, 'hello'}
# union
aset | {7, 8}  # {(1, 2), 1, 2, 3, 'hello', 7, 8}
# intersection
aset & {7, 8}  # set()
</code>

Below is a comparison of the data types mentioned above:

Stack

A stack is a linear data structure that stores items in a last‑in‑first‑out (LIFO) order. Python does not have a built‑in stack type.

Stack implementation:

<code>class Stack:
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def push(self, item):
        self.items.append(item)
    def pop(self):
        return self.items.pop()
    def peek(self):
        return self.items[len(self.items)-1]
    def size(self):
        return len(self.items)
</code>

Example usage:

<code>stack = Stack()
stack.push('Red')
stack.push('Green')
stack.push('Blue')
stack.push('Yellow')
# stack now ['Red', 'Green', 'Blue', 'Yellow']
stack.pop()   # removes 'Yellow'
stack.size() # 3
</code>

Queue

A queue stores elements in a first‑in‑first‑out (FIFO) order.

<code>class Queue(object):
    def __init__(self):
        self.items = []
    def isEmpty(self):
        return self.items == []
    def enqueue(self, item):
        self.items.insert(0, item)
    def dequeue(self):
        return self.items.pop()
    def size(self):
        return len(self.items)
</code>

Example usage:

<code>queue = Queue()
queue.enqueue('Red')
queue.enqueue('Green')
queue.enqueue('Blue')
queue.enqueue('Yellow')
# queue now ['Yellow', 'Blue', 'Green', 'Red']
queue.dequeue()  # removes 'Red'
queue.size()    # 3
</code>

References

Imran Ahmad, "40 Algorithms Every Programmer Should Know: Hone your problem‑solving skills by learning different algorithms and their implementation in Python"

"真的这么神奇吗 《程序员必会的40种算法》", https://blog.csdn.net/lose_user___/article/details/122437832

Pythondata structuresAlgorithmsListsQueuesStacks
Model Perspective
Written by

Model Perspective

Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.