Sets and tuples

Introduction to Python for Developers

George Boorman

Curriculum Manager, DataCamp

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 an attendee set
attendees_set = {"John Smith", "Alan Jones", "Roger Thompson",
                 "John Smith", "Brandon Sharp", "Sam Washington"}
print(attendees_set)
{'Alan Jones', 'Brandon Sharp', 'John Smith',
 'Roger Thompson', 'Sam Washington'}
Introduction to Python for Developers

Converting to a set

# Existing list variable
attendees_list = ["John Smith", "Alan Jones", "Roger Thompson",
                  "John Smith", "Brandon Sharp", "Sam Washington"]


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

Converting to a set

print(attendees_set)
{'Sam Washington', 'Roger Thompson', 'Alan Jones', 'John Smith', 'Brandon Sharp'}
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
attendees_set[0]
TypeError: 'set' object is not subscriptable
Introduction to Python for Developers

Sorting a set

attendees_set = {"John Smith", "Alan Jones", "Roger Thompson",
                 "John Smith", "Brandon Sharp", "Sam Washington"}


# Sorting a set sorted(attendees_set)
['Alan Jones', 'Brandon Sharp', 'John Smith', 'Roger Thompson', 'Sam Washington']
  • 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]

Padlock on top of a laptop

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

Creating a tuple

# Creating a tuple
office_locations = ("New York City", "London", "Leuven")


# Convert another data structure to a tuple attendees = tuple(attendees_list)
Introduction to Python for Developers

Accessing tuples

# Access the second element
office_locations[1]
"London"
Introduction to Python for Developers

Data structures summary

Data structure Syntax Immutable Allow duplicate values Ordered Subset with []
List [1, 2, 3] No Yes Yes Yes - index
Dictionary {key:value} No Yes Yes Yes - key
Set {1, 2, 3} No No No No
Tuple (1, 2, 3) Yes Yes Yes Yes - index
Introduction to Python for Developers

Let's practice!

Introduction to Python for Developers

Preparing Video For Download...