In Python, data structures are fundamental constructs used to store, organize, and manipulate data efficiently. Here are some common data structures available in Python:
[ ] and can contain elements of different data types.( ) and can contain elements of different data types.{ } with key-value pairs separated by colons : (e.g., {key1: value1, key2: value2}).{ } or the set() constructor.array module or third-party libraries like NumPy.queue module, or deque from the collections module.deque class from the collections module.These data structures provide different ways to organize and manipulate data in Python, each with its own advantages and use cases. Choosing the right data structure depends on factors such as the nature of the data, the operations to be performed, and efficiency considerations.
Example:
# Example program using lists
numbers = [1, 2, 3, 4, 5]
fruits = ['apple', 'banana', 'orange']
# Adding elements to a list
numbers.append(6)
fruits.insert(2, 'grape')
# Accessing elements by index
print(numbers[2]) # Output: 3
print(fruits[-1]) # Output: grape
# Iterating over elements
for fruit in fruits:
print(fruit)
# Removing elements
numbers.remove(3)
del fruits[0]
# Slicing
print(numbers[1:4]) # Output: [2, 4, 5]
# Example program using dictionaries
student = {'name': 'Alice', 'age': 20, 'grade': 'A'}
# Accessing values by key
print(student['name']) # Output: Alice
print(student.get('age')) # Output: 20
# Adding a new key-value pair
student['city'] = 'New York'
# Iterating over key-value pairs
for key, value in student.items():
print(key, ':', value)
# Removing a key-value pair
del student['grade']
# Example program using sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Union of sets
union = set1 | set2
# Intersection of sets
intersection = set1 & set2
# Difference of sets
difference = set1 - set2
# Symmetric difference of sets
sym_difference = set1 ^ set2
print(union)
print(intersection)
print(difference)
print(sym_difference)
# Example program using queues
from collections import deque
queue = deque(['a', 'b', 'c'])
# Enqueue
queue.append('d')
# Dequeue
item = queue.popleft()
print(item) # Output: a
# Example program using stacks
stack = []
# Push
stack.append('a')
stack.append('b')
# Pop
item = stack.pop()
print(item) # Output: b