Data+Structures+in+Python
Data+Structures+in+Python
Creating a List:
numbers = [1, 2, 3, 4, 5]
mixed = [10, "hello", 3.14]
my_list = [1, 2, 3]
my_list.append(4) # [1, 2, 3, 4]
my_list.insert(1, 99) # [1, 99, 2, 3, 4]
my_list.remove(2) # [1, 99, 3, 4]
my_list.pop() # Removes last element -> [1, 99, 3]
my_list.reverse() # [3, 99, 1]
my_list.sort() # [1, 3, 99]
Tuples are ordered but immutable collections (cannot be changed after creation).
Creating a Tuple:
print(my_tuple[1]) # Output: 20
Tuple Unpacking:
a, b, c = my_tuple
print(a, b, c) # Output: 10 20 30
my_tuple = (1, 2, 2, 3, 4)
print(my_tuple.count(2)) # Output: 2
print(my_tuple.index(3)) # Output: 3
Why Use Tuples?
• Faster than lists (since they are immutable)
• Used as dictionary keys (since they are hashable)
• Safe from unintended modifications
Creating a Set:
my_set = {1, 2, 3, 4}
my_set.add(5) # {1, 2, 3, 4, 5}
my_set.remove(2) # {1, 3, 4, 5}
my_set.discard(10) # No error if element not found
my_set.pop() # Removes random element
Set Operations:
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
print(a.difference(b)) # {1, 2}
Creating a Dictionary:
Dictionary Comprehensions: