Python Diaries ….. Day 5

Tuple and Set

Nishitha Kalathil
5 min readSep 18, 2023

--

Welcome to Day 5 of Python Diaries!

Today’s class is all about exploring two important data structures in Python: tuples and sets.

Tuples

Tuples are similar to lists, but with one crucial difference: they are immutable. This means that once you create a tuple, you cannot change its contents. Tuples are incredibly useful for situations where you want to store a collection of items that shouldn’t be modified.

Creating Tuples

Tuples are created by enclosing a sequence of elements within parentheses () and separating them with commas.

# Example of a tuple of numbers
numbers = (1, 2, 3, 4, 5)

# Example of a tuple of strings
fruits = ("apple", "banana", "cherry")

# Example of a mixed-type tuple
mixed = (1, "hello", 3.14, True)

Accessing Elements

You can access elements in a tuple using their index, just like in a list. Indexing starts at 0 for the first element.

numbers = (1, 2, 3, 4, 5)

first_element = numbers[0] # Output: 1
second_element = numbers[1] # Output: 2

Immutability of Tuples

As mentioned earlier, tuples are immutable, which means you cannot change the values of the elements after the tuple is created. This makes tuples useful for situations where you want to ensure that the data remains constant.

numbers = (1, 2, 3)
numbers[0] = 10 # This will raise a TypeError: 'tuple' object does not support item assignment

Tuple Operations

Tuples support operations like indexing, slicing, and finding the length. However, they do not support methods like append(), remove(), or pop() because those would involve modifying the tuple.

numbers = (1, 2, 3, 4, 5)

# Indexing
first_element = numbers[0] # Output: 1

# Slicing
subset = numbers[1:4] # Output: (2, 3, 4)

# Length
length = len(numbers) # Output: 5

When to Use Tuples

  • Use tuples when you want to represent a collection of items that should not be changed.
  • Tuples are often used for returning multiple values from a function.
  • They are also used for situations where you want to ensure the integrity of a sequence of data.

Sets

Sets are another fundamental data structure in Python. They are unordered collections of unique elements. Sets are particularly powerful when you need to perform operations like unions, intersections, and differences between collections of data.

Let’s dive into both tuples and sets, and learn how to use them effectively in your Python programs. Get ready to expand your toolkit for data management! Let’s get started!

Creating Sets

Sets are created by placing a comma-separated sequence of elements within curly braces {}.

# Example of a set of numbers
numbers = {1, 2, 3, 4, 5}

# Example of a set of strings
fruits = {"apple", "banana", "cherry"}

# Example of a mixed-type set
mixed = {1, "hello", 3.14, True}

Unique Elements

Sets automatically eliminate duplicates. If you try to add a duplicate element, it won’t be included in the set.

numbers = {1, 2, 3, 2, 1}
print(numbers) # Output: {1, 2, 3}

Modifying Sets

You can add and remove elements from a set.

fruits = {"apple", "banana"}

# Adding an element
fruits.add("cherry") # fruits is now {"apple", "banana", "cherry"}

# Removing an element
fruits.remove("banana") # fruits is now {"apple"}

Set Methods

Sets have various methods for performing operations like adding, removing, and checking membership.

fruits = {"apple", "banana"}

# Adding elements
fruits.update({"cherry", "orange"}) # fruits is now {"apple", "banana", "cherry", "orange"}

# Removing an element
fruits.discard("banana") # fruits is now {"apple", "cherry", "orange"}

# Checking membership
is_present = "apple" in fruits # Output: True

# issubset():Returns True if all elements of the set are present in another set (the argument).
is_subset = set1.issubset(set2)

# issuperset(): Returns True if all elements of another set (the argument) are present in the set.
is_superset = set1.issuperset(set2)

# isdisjoint(): Returns True if two sets have no elements in common.
is_disjoint = set1.isdisjoint(set2)

Set Operations

Sets support various operations like union, intersection, and difference.

Union: The union of two sets contains all unique elements from both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using the union method
union_set = set1.union(set2)

# Using the | operator (pipe)
union_set = set1 | set2

# Using the update method
set1.update(set2)

Intersection: The intersection of two sets contains elements that are present in both sets.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}

# Using the intersection method
intersection_set = set1.intersection(set2)

# Using the & operator (ampersand)
intersection_set = set1 & set2

# The intersection_update method updates the set it's called on with the intersection of itself and another set (or any iterable).
set1.intersection_update(set2)

Difference: The difference of two sets contains elements that are present in the first set but not in the second set.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}

# Using the difference method
difference_set = set1.difference(set2)

# Using the - operator (minus)
difference_set = set1 - set2

# The difference_update method updates the set it's called on
# with the elements that are present in the set but not in another
# set (or any iterable).
set1.difference_update(set2) # output {1, 2}

Symmetric Difference: The symmetric difference of two sets contains elements that are in either of the sets, but not in their intersection.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5}

# Using the symmetric_difference method
symmetric_difference_set = set1.symmetric_difference(set2)

# Using the ^ operator (caret)
symmetric_difference_set = set1 ^ set2

# The symmetric_difference_update method updates the set it's
# called on with the symmetric difference of itself and another
# set (or any iterable).
set1.symmetric_difference_update(set2)

When to Use Sets

  • Use sets when you want to store a collection of unique elements.
  • Sets are particularly useful for tasks like finding common elements between multiple collections of data.

By mastering tuples and sets, you’ve added valuable tools to your Python programming repertoire. As you continue your journey, remember to choose the right data structure for the task at hand, maximizing your code’s efficiency and readability.

You can access the other topics in this tutorial series right here:

In the next class, we’ll explore more advanced data structures. Keep up the great work! Happy coding!

--

--