Conversation with Merlin [email protected] · Fri Dec 15 2023

write 50 python code snippets data structures

Certainly! Here are 50 Python code snippets covering various data structures:

  1. List creation with integers:
my_list = [1, 2,3, 4, 5]
  1. List creation with strings:
names = ['Alice',Bob', 'Charlie', 'David']
  1. Accessing list elements```python print(my_list[0]) # Output: 1
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)
  1. creation:
my_tuple = (1, 2, 3, 4 5)
  1. Accessing tuple elements:
print(my[2]) # Output: 3

. Modifying tuple elements (not allowed).

  1. Dictionary creation:
my_dict = {'a': , 'b': 2, 'c': 3}
  1. Accessing dictionary values:
print(my_dictb']) # Output: 2
  1. Modifying dictionary values:
_dict['c'] = 30 print(my_dict) # Output:a': 1, 'b': 2, 'c 30}
  1. Set creation:
my_set = {1, 2, 3, 4, 5}
  1. Adding elements to set:
my_set.add(6) print(my_set) #: {1, 2, 3, 4,5, 6}
  1. Set operations:
set1 = {1, 2,3} set2 = {3, 4, 5intersection = set1 & set2 print(intersection) # Output: {3}
  1. Stack implementation using list:
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': [] }
  1. Matrix creation:
matrix = [[1, 2, 3], [4, 5 6], [7, 8, 9]] ``22. Accessing matrix elements: ```python print(matrix[1][2]) # Output:
  1. Modifying matrix elements:
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]
  1. Adding elements to a heap: python heapq.heappush(data, 7) print(data) # Output: [1, 2, 4,3, 6, 5, 7]
. 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')
  1. Implementing a stack using deque:
from collections import deque stack = deque()