Data Structures in Python

In this article, we'll take a closer look at the four built-in data structures in Python: lists, tuples, dictionaries, and sets. Each of these data structures has its own distinct characteristics and use cases, and you'll learn how to create and perform basic operations on each of them.

Table of contents

Lists

Lists are ordered collections of items that can be of any data type, including strings, integers, floats, and other lists. Lists are defined using square brackets and items are separated by commas. Lists can be mutable, meaning their elements can be added, removed, or modified after they are created.

my_list = [1, 2, 3, 4, 5]

For more details about Lists in Python, read our article "Everything About Lists in Python".

Tuples

Tuples are similar to lists, but they are immutable, meaning their elements cannot be modified after they are created. If you try to modify an element of a Tuple, you will get a TypeError . Tuples are defined using parentheses () and items are separated by commas.

my_tuple = (1, 2, 3, 4, 5)

For more details about Tuples in Python, read our article "Everything About Tuples in Python".

Sets

Sets are unordered collections of unique items, and they can contain only unique items. Sets are defined using curly braces {} and items are separated by commas.

my_set = {1, 2, 3, 4, 5}

You can add items to a set using the add() method:

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)  # [1, 2, 3, 4]

You can remove items from a set using the discard() method:

my_set = {1, 2, 3, 4}
my_set.discard(2)
print(my_set)  # [1, 3, 4]

You can combine the elements of two sets using the union() method:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.union(set2)
print(result)  # {1, 2, 3, 4, 5}

Dictionaries

Dictionaries are unordered collections of key-value pairs, where each key is unique and maps to a specific value. Dictionaries are defined using curly braces {} and keys are separated from values using a colon (:).

my_dict = {"foo": "bar", "number": 42, "hallo": "World"}