Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Introduction to Python
  5. Values and Types
  6. Set Data Type

Set Data Type

  • A set is a collection which is unordered and unindexed.
  • Sets are written within curly brackets
  • Once a set is created, it cannot be changed but it is possible to add new items
  • A set does not contain any duplicate values or elements

Some operations

Creating a Set

Creating the set with elements of different data types

Example

>>> first_set = {"python","chemistry","maths"}
>>> print(first_set)
{'python', 'chemistry', 'maths'}

Add Items

To add one item to a set

Example

>>> first_set.add("35.0")
>>> print(first_set)
{'35.0', 'python', 'chemistry', 'maths'}

Union

  • Union operation performed on two sets and returns all the elements from both the sets.
  • It is performed by using | operator

Example

>>> set1 = {1,2,4,2,5,6,7,8,1}
>>> set2 = {1,9,4,3,2,7}
>>> set1
{1, 2, 4, 5, 6, 7, 8}
>>> set2
{1, 2, 3, 4, 7, 9}
>>> print(set1 | set2)
{1, 2, 3, 4, 5, 6, 7, 8, 9}

Intersection

  • Intersection operation performed on two and returns the elements which are common in both the sets.
  • It is performed by using & operator

Example

>>> print(set1 & set2)
{1, 2, 4, 7}

Difference

  •  Difference operation performed on two sets set 1 and set 2 returns the elements which are present on set 1but not in set 2
  • It is performed using – operator

Example

>>> print(set1 - set2)
{8, 5, 6}

Symmetric Difference

  • Symmetric difference operation performed on two sets returns the elements which are present in either set 1 or set 2 but not in both.
  • It is performed by using ^ operator

Example

>>> print(set1 ^ set2)
{3, 5, 6, 8, 9}

Loading

Views: 2

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments