Data Structures with Python
Data structures with Python
Data structures are specific ways of arranging and storing collections of data, so that data can be organized and manipulated efficiently. Stack, Queue, Linked List and Tree are some of the most common language-independent data structures (Abstract data types).
Moreover, every programming language has its own implementations of specific data structures. Python has four built-in data structures; List, Tuple, Set and Dictionary. So, today let’s compare and contrast these four data structures.
List
Lists are ordered (maintain the order of insertion), mutable (items can be modified after insertion) and indexed (can access elements based on position, i.e. index) collections of data. We can store data of the same type or of different types. Lists allow storing duplicate values.
greetings = ["Hello", 123, 1.0]
print(f"Before: {greetings}")
greetings[1] = "Hola"
greetings[2] = "Bonjour"
print(f"After: {greetings}")
An empty list can be created in two ways; using empty square brackets and the list() constructor. Values can be added with append() or insert() function. Refer Python Documentation for more List methods.
empty_list_1 = []
empty_list_2 = list()
empty_list_1.append("Hello")
empty_list_2.insert(0, "Hola")
A list can be used when data needs to be stored in a simple collection which needs frequent modifications.
Tuple
Tuples are ordered, immutable and indexed collections of data. We can store data of the same type or of different types. Tuples allow storing duplicate values.
So, lists and tuples are similar except that tuple values cannot be modified (immutable). Therefore, tuples are more efficient in terms of memory usage and performance than lists.
codes = ('A', 65, 'Z', 90.0)
Unlike lists, parentheses are used to create empty tuples. Similar to lists, tuple() constructor can also be used to create empty tuples.
empty_tuple_1 = ()
empty_tuple_2 = tuple()
Since tuples are immutable, we have to convert tuples to lists in order to add values or modify values. Then, the list can be converted back to a tuple after modification.
# add values
temp_list = list(empty_tuple_1)
temp_list.append("Hello")
empty_tuple_1 = tuple(temp_list)
# modify values
temp_list = list(codes)
temp_list[3] = 90
empty_tuple_2 = tuple(temp_list)
print(empty_tuple_1)
print(empty_tuple_2)
A tuple can be used to store data that doesn’t need modification or to store temporary data.
Set
Sets are unordered, mutable and unindexed collection of data. We can store data of the same type or of different types. Sets don’t allow storing duplicate values.
Since sets are both unordered and unindexed, the data within a set will exhibit a different order each time it is accessed.
misc = {'A', 9.0, 4}
An empty set can be created by only using the set() constructor. Empty curly braces are used to create dictionaries. Values can be added with the add() function.
empty_set = set()
empty_set.add(3.14)
Since sets only allow unique values, sets can be used to remove duplicate values from lists.
duplicates_list = [1, 2, 3, 2, 1]
unique_set = set(duplicates_list)
print(duplicates_list)
print(unique_set)
A set can be used to store unique data values and when data need to be accessed randomly.
Dictionary
Dictionaries are ordered (Version 3.7+), mutable and unindexed (cannot access elements based on position) collections of data. We can store data of the same type or of different types. Dictionaries do not allow storing duplicate values.
A dictionary store items in key: value pairs. Hence, items can be accessed using keys, though dictionary is not indexed in a traditional way like a list.
dictionary_1 = {
'H': 72,
'E': 69,
'L': 76,
'O': 79
}
An empty dictionary can be created in two ways; using empty curly braces and the dict() constructor. Values can be added by adding keys and assigning values to them.
empty_dict_1 = {}
empty_dict_2 = dict()
empty_dict_1["en"] = "Hello"
Since dictionaries use key-value pairs, they can be used to store table-like data or collections of different types of data. Below example shows a 'students' dictionary which has student IDs for keys. Each value is a list with student details. Each list contains a student name (str), their test scores (tuple) and the average (float).
students = {
"001": ["Jenna", (85, 90, 79), 84.7],
"002": [ "Tom", (73, 95, 88), 85.3]
}
print(students["001"])
A dictionary can be used when data needs to be stored in key-value pairs for fast lookup or to store frequency values.
Summary of Comparison
| List | Tuple | Set | Dictionary |
|---|---|---|---|
| Ordered | Ordered | Unordered | Ordered |
| Mutable | Immutable | Mutable | Mutable |
| Duplicate | Duplicate | Unique | Unique |
| Indexed | Indexed | Unindexed | Unindexed |
Comments
Post a Comment