Sets in python

This recipe explains what are sets in python , how to create them and how to add elements to them

Create and append to sets in Python

Hello Pythoneers! In this tutorial, we will be understand one of the interesting datatype in python called sets and how to create them. Sets are nothing but unordered collection of items. Sets can have only unique values and duplicates can not be included in a set. Another important to note about set elements is that sets are immutable. However, A set itself is mutable. For example, we can add or delete elements from them.

Creating a set

Sets can be created in python in different ways such as either using a pair of curly braces or using the set() function as shown below.

    ## Creating a set
    # Using {}
    set1 = {1,2,3,4,5,'ProjectPro'}
    print(set1)
    # Using set() function
    set2 = set([1,2,'ProjectPro'])
    print(set2)

Output

    {1, 2, 3, 4, 5, 'ProjectPro'}
    {1, 2, 'ProjectPro'}
    Traceback (most recent call last):
    File "sets_code.py", line 11, in 
        set3 = {1, 2, [10, 20]}
    TypeError: unhashable type: 'list'

 

Note : To create an empty set, use the set() function. Assigning a pair of empty curly braces to a variable creates an empty dictionary. Sets are mutable but since they are unordered indexing is not an option. But you can still add or remove elements as shown below.

Adding elements to a set

There are bunch of options available to add elements to a set. The add() function can be used to add a single element to the set while the update() function is used to add multiple elements at once to the set.

    ## Adding elements to set
    mySet = {10,20,30}

    # Adding one element
    mySet.add(2)
    print("Adding 2 to mySet ",mySet)

    # Adding multiple elements
    mySet.update([11, 22, 33, 'ProjectPro', 10])
    print("Adding [11,22,33,ProjectPro,10] to mySet ",mySet)
    

 

 

Download Materials

What Users are saying..

profile image

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

AWS MLOps Project to Deploy a Classification Model [Banking]
In this AWS MLOps project, you will learn how to deploy a classification model using Flask on AWS.

Build Piecewise and Spline Regression Models in Python
In this Regression Project, you will learn how to build a piecewise and spline regression model from scratch in Python to predict the points scored by a sports team.

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.

Build a Multi-Class Classification Model in Python on Saturn Cloud
In this machine learning classification project, you will build a multi-class classification model in Python on Saturn Cloud to predict the license status of a business.

Build a Text Classification Model with Attention Mechanism NLP
In this NLP Project, you will learn to build a multi class text classification model with attention mechanism.

Build Portfolio Optimization Machine Learning Models in R
Machine Learning Project for Financial Risk Modelling and Portfolio Optimization with R- Build a machine learning model in R to develop a strategy for building a portfolio for maximized returns.

Multi-Class Text Classification with Deep Learning using BERT
In this deep learning project, you will implement one of the most popular state of the art Transformer models, BERT for Multi-Class Text Classification

Time Series Forecasting Project-Building ARIMA Model in Python
Build a time series ARIMA model in Python to forecast the use of arrival rate density to support staffing decisions at call centres.