A tuple is an ordered, immutable collection of elements. Its immutability ensures that, once created, the elements within a tuple cannot be altered.
Tuples are created using parentheses ()
and separating items with commas.
colors = ("red", "blue", "green")
A tuple with a single item has a trailing comma to differentiate it from a regular value.
single_element_tuple = ("red",)
Like lists, elements in a tuple can be accessed by their index.
print(colors[0]) # Outputs: red
more_colors = colors + ("yellow", "pink")
print(more_colors) # Outputs: ('red', 'blue', 'green', 'yellow', 'pink')
doubled_colors = colors * 2
print(doubled_colors) # Outputs: ('red', 'blue', 'green', 'red', 'blue', 'green')
print("red" in colors) # Outputs: True
print(len(colors)) # Outputs: 3
Since tuples are immutable, they have fewer built-in methods compared to lists.
position = colors.index("green")
print(position) # Outputs: 2
num_red = colors.count("red")
print(num_red) # Outputs: 1
A set is an unordered collection of unique items. Sets are used for membership testing, removing duplicates from sequences, and mathematical operations like unions, intersections, and differences.
Sets are created using curly braces {}
.
fruits = {"apple", "banana", "cherry"}
Using the set()
function, you can create sets from other data types:
list_fruits = ["apple", "banana", "cherry", "apple"]
fruits_set = set(list_fruits)
print(fruits_set) # Outputs: {'cherry', 'banana', 'apple'}
fruits.add("grape")
print(fruits) # Outputs: {'grape', 'cherry', 'banana', 'apple'}
fruits.remove("banana")
fruits.discard("banana")
random_fruit = fruits.pop()
fruits.clear()
fruits = {"apple", "banana", "cherry"}
berries = {"strawberry", "blueberry"}
all_fruits = fruits.union(berries)
common_fruits = fruits.intersection(berries)
exclusive_fruits = fruits.difference(berries)
Both tuples and sets are fundamental data structures in Python. Tuples offer immutable, ordered collections, making them ideal for fixed sequences of items. In contrast, sets provide powerful tools for handling unique items and conducting set-theoretic operations, making them invaluable for various computational tasks. Familiarity with both structures broadens your capabilities as a Python programmer.