A data structure is a way of organizing and storing data so that they can be accessed and worked with efficiently. They define the relationship between the data, and the operations that can be performed on the data.
In Python, some built-in data structures include:
- Lists: ordered collection of items (which can be of different types)
- Tuples: ordered, immutable collection of items (which can be of different types)
- Sets: unordered collection of unique items
- Dictionaries: unordered collection of key-value pairs
- Trees: hierarchical data structure that stores information in nodes
- Stacks: last-in-first-out (LIFO) data structure
- Queues: first-in-first-out (FIFO) data structure
When choosing a data structure, consider the following factors:
- The type of data you are working with
- The operations you need to perform on the data
- The efficiency, usability, and scalability of the data structure
Characteristics of data structures:
- They allow you to organize data in a way that makes it easy to access, modify, and search.
- They have specific operations that can be performed on them, such as insertion, deletion, and traversal.
- They have a specific memory representation, which affects their performance in terms of time and space complexity.
Operations performed on data structures:
- Insertion: adding an element to the data structure
- Deletion: removing an element from the data structure
- Traversal: accessing each element in the data structure
- Searching: finding a specific element in the data structure
- Sorting: arranging the elements in a specific order
- Merging: combining two data structures into one
Example of data structure operation in python:
List:
- Insertion: my_list.append(5)
- Deletion: del my_list[0]
- Traversal: for i in my_list: print(i)
- Searching: if 5 in my_list: print("Found")
- Sorting: my_list.sort()
- Merging: my_list1 + my_list2
Tuple:
- Traversal: for i in my_tuple: print(i)
- Searching: if 5 in my_tuple: print("Found")
Set:
- Insertion: my_set.add(5)
- Deletion: my_set.remove(5)
- Traversal: for i in my_set: print(i)
Dictionary:
- Insertion: my_dict["key"] = 5
- Deletion: del my_dict["key"]
- Traversal: for key, value in my_dict.items(): print(key, value)
- Searching: if "key" in my_dict: print("Found")
Tree:
- Insertion: my_tree.insert(5)
- Deletion: my_tree.delete(5)
- Traversal: for i in my_tree: print(i)
Stack:
- Insertion: my_stack.push(5)
- Deletion: my_stack.pop()
- Traversal: for i in my_stack: print(i)
Queue:
- Insertion: my_queue.enqueue(5)
- Deletion: my_queue.dequeue()
- Traversal: for i in my_queue: print(i)