write 50 python code snippets data structures
Certainly! Here are 50 Python code snippets covering various data structures:
my_list = [1, 2,3, 4, 5]
names = ['Alice',Bob', 'Charlie', 'David']
4. Modifying list elements: ```pythonmy_list[2] = 10 print(my_list # Output: [1, 2, 10, 4, 5] ``5. List slicing: ```python print(my_list[1:3]) # Output: [2, 10] ` 6. List concatenation: ```python combined_list my_list + names print(combined_list)
my_tuple = (1, 2, 3, 4 5)
print(my[2]) # Output: 3
. Modifying tuple elements (not allowed).
my_dict = {'a': , 'b': 2, 'c': 3}
print(my_dictb']) # Output: 2
_dict['c'] = 30 print(my_dict) # Output:a': 1, 'b': 2, 'c 30}
my_set = {1, 2, 3, 4, 5}
my_set.add(6) print(my_set) #: {1, 2, 3, 4,5, 6}
set1 = {1, 2,3} set2 = {3, 4, 5intersection = set1 & set2 print(intersection) # Output: {3}
stack = [] stack.append(1) stack.append2) print(stack.pop()) # Output: 2
17 Queue implementation using deque:
from collections import deque queue = deque() queue.append(1) queue(2) print(queue.popleft()) # Output: 1 ``18. Linked list node class: ```python class Node: def __init__(self, data): self.data = data self.next = None ` 19. Binary tree node class: ```python class: def __init__(self, data): self.data = data .left = None self.right = None
. Graph representation using adjacency list:
graph = { 'A': ['B', ''], 'B': ['D'], 'C': ['E'], 'D': ['F'], 'E': ['F'], 'F': [] }
matrix = [[1, 2, 3], [4, 5 6], [7, 8, 9]] ``22. Accessing matrix elements: ```python print(matrix[1][2]) # Output:
matrix[0][1] = 10 print(matrix) # Output: [[1 10, 3], [4, 5, 6], [7, 8, 9]] ``24. Creating a heap: ```python import heapq = [3, 2, 5, 1, 6, 4] heapq.heapify(dataprint(data) # Output: [1, 2, 4, 3, 6, 5]
. Priority queue using heapq: ```python priority_queue =heapq.heappush(priority_queue, (2, 'task2')) heapq.heappush(priority_queue, (1, 'task1')) print(heapqappop(priority_queue)) # Output: (1,task1')
from collections import deque stack = deque()