6 Essential Concepts of Sets & Tuples in Python

Learn in 6 quick easy steps what are python’s sets and tuples data structures. In today’s article I am going to share the 6 essential concepts of sets & tuples in Python for data science. You will more often deal with these concepts  in data visualization & analysis with python.

SETS – OVERVIEW

Sets in Python are collections of unique elements. They’re super handy for dealing with distinct values and quick membership checks.

# Creating a Set
fruits = {apple, banana, Orrange}


# Adding to a Set
fruits.add(mango)


# Removing from a Set
fruits.remove(banana)

SETS – SET OPERATIONS

Sets support various operations like union, intersection, and difference, making them great for comparisons and data manipulation.

first_set = {1, 2, 3}
second_set = {3, 4, 5}


union_set = set_A | set_B
intersection_set = set_A & set_B
difference_set = set_A - set_B

SETS – PRACTICAL EXAMPLE

Imagine dealing with survey responses. Sets can quickly help you find unique choices across responses.

responses = ['Yes' , 'No', 'Yes', 'Maybe', 'No']
unique_responses = set(responses)

TUPLES – OVERVIEW

Tuples are similar to lists but are immutable, meaning their elements can’t be changed after creation. They’re great for grouping related data.

# Creating a Tuple
point = (3, 7)


#Unpacking a Tuple
x, y = point

TUPLES – USE CASES

Tuples shine when you need to represent data that shouldn’t change, like coordinates or data records. They’re memory efficient too!

# Data Record Tuple
srudent = ('Alice', 22, 'Computer Science')

SETS VS. TUPLES

Choosing between sets and tuples? Sets for unique, fast membership checks. Tuples for unchangeable, ordered data. Both have their roles!

# Set for membership check
if 'apple' in fruits:
  print("We have apples!")


  # Tuple for ordered data
  first_name, age, _ = student

Leave a Comment