Programming Essentials Python - Manipulating Collections - Getting Unique Elements

Let us perform few tasks to understand how to extract unique elements. We can use either of these approaches.

  • We can create a list of elements first and then convert into a set.

  • We can also build set directly while extracting the information.

Key Concepts Explanation

Key Concept 1

In this task, we will extract unique dates from the orders data using Python. We will read the orders data from a file, split the data to extract the dates, and then create a set to store only unique dates.

# Read orders data from a file
orders_file = open(path)
orders_raw =
orders = orders_raw.splitlines()

# Extracting unique dates using set()
order_dates = {order.split(',')[1] for order in orders}

Key Concept 2

For this task, we will focus on extracting unique weekend dates from the orders data. We will check each date to determine if it falls on a weekend (Saturday or Sunday), and then store only the unique weekend dates in a set.

import datetime as dt

def is_weekend(order_date):
    return dt.datetime.strptime(order_date, '%Y-%m-%d %H:%M:%S.%f').weekday() in (5, 6)

weekend_dates = set()

for order in orders:
    order_date = order.split(',')[1]

    if is_weekend(order_date):

Hands-On Tasks

  1. Get all the unique dates from orders data.
  2. Get all the unique weekend dates from orders data.


In this article, we learned how to extract unique elements from a dataset using Python and how to specifically target and store only the unique dates and weekend dates from a list of orders. We encourage you to practice these tasks and engage with the community for further learning.

Watch the video tutorial here