Tuples, sets/shaare/2QdV2w
Tuples (tuple)
Tuples are ordered, immutable sequences defined with parentheses (). Once created, their contents cannot be changed.
Characteristics and Use Cases
- Ordered: items maintain position
- Immutable: cannot add, remove, or change after creation
- Useful for fixed records like coordinates, version numbers, or as dictionary keys
host_port = ("127.0.0.1", 3000)
red_rgb = (255, 0, 0)
tuple_single_value = ("only-value",) # To create a single-item tuple, add a trailing comma
print(type(host_port))
print(type(tuple_single_value))
print(f"Host: {host_port[0]}")
print(red_rgb[-2:])
print(type(red_rgb[-2:]))
# host_port[0] = "192.168.1.1" # Uncommenting will raise a TypeError because tuples are immutable
Sets (set)
- Characteristics: Unordered, Mutable, Unique items only (duplicates removed)
- The items of a set must be immutable.
- Use Cases: Membership testing, removing duplicates, set operations (union, intersection, difference).
Set Operations
- Membership Testing: Check if an item exists in a set using the
inkeyword. - Adding Items: Use
add()to add an item to a set. - Removing Items: Use
remove()to remove an item (raises an error if the item doesn't exist) ordiscard()to remove an item (doesn't raise an error if the item doesn't exist). - Set Operations:
- Union: Combine all unique items from two sets using
union()or|. - Intersection: Find common items between two sets using
intersection()or&. - Difference: Find items in one set but not in another using
difference()or-.
- Union: Combine all unique items from two sets using
unique_ports = set([80, 443, 22, 80, 8080, 443])
server_names = {"web01", "web02"}
print(unique_ports)
print(22 in unique_ports)
print(22 in server_names)
unique_ports.add(3000)
print(unique_ports)
unique_ports.remove(22)
print(unique_ports)
# unique_ports.remove(22) # Will raise KeyError because item 22 is not in the set anymore
unique_ports.discard(22)
print(unique_ports)
# set_of_lists = set([[1, 2], [3, 4]]) # Will throw a TypeError, since lists are mutable
# set_of_sets = {{1, 2}, {3, 4}} # Will throw a TypeError, since sets are mutable
set_of_tuples = {(1, 2), (3, 4)}
print(set_of_tuples)
print((1, 2) in set_of_tuples)
print((1, 3) in set_of_tuples)
(97)