Sets and tuples

Introduction to Python for Developers

Jasmin Ludolf

Senior Data Science Content Developer

Sets

  • Contain unique data

  • Unchangeable

    • Can add or remove values, but cannot change them
  • Ideal to identify and remove duplicates

  • Quick to search (compared to other data structures such as lists)

Introduction to Python for Developers

Creating a set

  • Set = {}
  • : = Dictionary
  • No : = Set
# Create a set of ingredients
ingredients = {"pasta", "tomatoes", "pasta", 
                 "basil", "garlic", "olive oil", "salt"}
print(ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil', 'salt'}
Introduction to Python for Developers

Converting to a set

# Existing list variable
ingredients_list = ["pasta", "tomatoes", "garlic", "basil"
                    "olive oil", "pasta", "salt"]


# Convert to a set unique_ingredients = set(ingredients_list)
# Check the data type type(unique_ingredients)
set
Introduction to Python for Developers

Converting to a set

print(unique_ingredients)
{'pasta', 'tomatoes', 'garlic', 'basil', 'olive oil'}
Introduction to Python for Developers

Limitations of sets

  • Don't have an index
    • Can't have duplicates
    • Can't subset with []
# Trying to subset a set
print(unique_ingredients[0])
TypeError: 'set' object is not subscriptable
Introduction to Python for Developers

Sorting a set

ingredients = {"pasta", "tomatoes", "garlic", 
                 "basil", "olive oil", "salt"}


# Sorting a set print(sorted(ingredients))
['basil', 'garlic', 'olive oil', 'pasta', 'salt', 'tomatoes']
  • sorted() returns a list
Introduction to Python for Developers

Tuples

  • Immutable - cannot be changed
    • No adding values
    • No removing values
    • No changing values

 

  • Ordered
    • Can subset by index i.e., [0]

 

  • Useful for location information or identifiers

Padlock on top of a laptop

1 https://unsplash.com/@towfiqu999999
Introduction to Python for Developers

Creating a tuple

# Creating a tuple
serving_sizes = (1, 2, 4, 6, 8)


# Convert another data structure to a tuple ingredients_tuple = tuple(ingredients_list)
Introduction to Python for Developers

Accessing tuples

# A tuple
serving_sizes = (1, 2, 4, 6, 8)

# Access the second element
print(serving_size[1])
2
Introduction to Python for Developers

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...