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

Ray han

Tech Leader | Stanford / Yale University
linkedin profile url

I think that they are fantastic. I attended Yale and Stanford and have worked at Honeywell,Oracle, and Arthur Andersen(Accenture) in the US. I have taken Big Data and Hadoop,NoSQL, Spark, Hadoop... Read More

Relevant Projects

Build a Graph Based Recommendation System in Python -Part 1
Python Recommender Systems Project - Learn to build a graph based recommendation system in eCommerce to recommend products.

Customer Churn Prediction Analysis using Ensemble Techniques
In this machine learning churn project, we implement a churn prediction model in python using ensemble techniques.

FEAST Feature Store Example for Scaling Machine Learning
FEAST Feature Store Example- Learn to use FEAST Feature Store to manage, store, and discover features for customer churn prediction machine learning project.

LLM Project to Build and Fine Tune a Large Language Model
In this LLM project for beginners, you will learn to build a knowledge-grounded chatbot using LLM's and learn how to fine tune it.

Ola Bike Rides Request Demand Forecast
Given big data at taxi service (ride-hailing) i.e. OLA, you will learn multi-step time series forecasting and clustering with Mini-Batch K-means Algorithm on geospatial data to predict future ride requests for a particular region at a given time.

Linear Regression Model Project in Python for Beginners Part 2
Machine Learning Linear Regression Project for Beginners in Python to Build a Multiple Linear Regression Model on Soccer Player Dataset.

Expedia Hotel Recommendations Data Science Project
In this data science project, you will contextualize customer data and predict the likelihood a customer will stay at 100 different hotel groups.

Build a CNN Model with PyTorch for Image Classification
In this deep learning project, you will learn how to build an Image Classification Model using PyTorch CNN

Time Series Python Project using Greykite and Neural Prophet
In this time series project, you will forecast Walmart sales over time using the powerful, fast, and flexible time series forecasting library Greykite that helps automate time series problems.

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS