Topic 2: Tuples and Sets

Tuples

1. Introduction

A tuple is an ordered, immutable collection of elements. Its immutability ensures that, once created, the elements within a tuple cannot be altered.

2. Creating Tuples

Tuples are created using parentheses () and separating items with commas.

python
colors = ("red", "blue", "green")

A tuple with a single item has a trailing comma to differentiate it from a regular value.

python
single_element_tuple = ("red",)
3. Accessing Elements

Like lists, elements in a tuple can be accessed by their index.

python
print(colors[0]) # Outputs: red
4. Tuple Operations
  • Concatenation: You can concatenate tuples.
python
more_colors = colors + ("yellow", "pink") print(more_colors) # Outputs: ('red', 'blue', 'green', 'yellow', 'pink')
  • Repetition: Tuples can be repeated.
python
doubled_colors = colors * 2 print(doubled_colors) # Outputs: ('red', 'blue', 'green', 'red', 'blue', 'green')
  • Membership: Check if an item exists in a tuple.
python
print("red" in colors) # Outputs: True
  • Length: Find the number of items in a tuple.
python
print(len(colors)) # Outputs: 3
5. Tuple Methods

Since tuples are immutable, they have fewer built-in methods compared to lists.

  • index(): Return the index of the first occurrence of a value.
python
position = colors.index("green") print(position) # Outputs: 2
  • count(): Count the occurrences of a value in the tuple.
python
num_red = colors.count("red") print(num_red) # Outputs: 1

Sets

1. Introduction

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.

2. Creating Sets

Sets are created using curly braces {}.

python
fruits = {"apple", "banana", "cherry"}

Using the set() function, you can create sets from other data types:

python
list_fruits = ["apple", "banana", "cherry", "apple"] fruits_set = set(list_fruits) print(fruits_set) # Outputs: {'cherry', 'banana', 'apple'}
3. Set Operations
  • Add: Add an item to the set.
python
fruits.add("grape") print(fruits) # Outputs: {'grape', 'cherry', 'banana', 'apple'}
  • Remove: Remove an item from the set. Raises an error if the element doesn’t exist.
python
fruits.remove("banana")
  • Discard: Remove an item from the set. Doesn’t raise an error if the element doesn’t exist.
python
fruits.discard("banana")
  • Pop: Remove and return a random element from the set.
python
random_fruit = fruits.pop()
  • Clear: Remove all elements from the set.
python
fruits.clear()
  • Union: Combine two sets.
python
fruits = {"apple", "banana", "cherry"} berries = {"strawberry", "blueberry"} all_fruits = fruits.union(berries)
  • Intersection: Find common items between two sets.
python
common_fruits = fruits.intersection(berries)
  • Difference: Get items that exist only in the first set and not in the second.
python
exclusive_fruits = fruits.difference(berries)
4. Conclusion

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.