Python Data Structures
# Dictionary
print(type({}))
print(type({1: 1}))
# Set
print(type({1}))
print(type(set()))
<class 'dict'>
<class 'dict'>
<class 'set'>
<class 'set'>
from collections import defaultdict
d = defaultdict(int)
d[3] += 1
print(d)
f = defaultdict(lambda: 0)
f[3] += 1
print(f)
defaultdict(<class 'int'>, {3: 1})
defaultdict(<function <lambda> at 0x7f1c43c3df70>, {3: 1})
import heapq
l = [1, 4, 3, 2, 35, 1]
heapq.heapify(l)
while len(l) > 0:
print(heapq.heappop(l))
1
1
2
3
4
35
from collections import deque
stack = deque()
# append() function to push element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack:')
print(stack)
# pop() function to pop element from stack in LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
# uncommenting print(stack.pop()) will cause an IndexError as the stack is now empty
Initial stack:
deque(['a', 'b', 'c'])
Elements popped from stack:
c
b
a
Stack after elements are popped:
deque([])
stack = []
# append() function to push element in the stack
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
# pop() function to pop element from stack in LIFO order
print('\nElements popped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are popped:')
print(stack)
# uncommenting print(stack.pop()) will cause an IndexError as the stack is now empty
Initial stack
['a', 'b', 'c']
Elements popped from stack:
c
b
a
Stack after elements are popped:
[]
from collections import deque
# Initializing a queue
q = deque()
# Adding elements to a queue
q.append('a')
q.append('b')
q.append('c')
print("Initial queue")
print(q)
# Removing elements from a queue
print("\nElements dequeued from the queue")
print(q.popleft())
print(q.popleft())
print(q.popleft())
print("\nQueue after removing elements")
print(q)
# Uncommenting q.popleft() will raise an IndexError as queue is now empty
Initial queue
deque(['a', 'b', 'c'])
Elements dequeued from the queue
a
b
c
Queue after removing elements
deque([])