Create Set in Python

Sets in Python are powerful data structure with several key properties and behaviors. Sets are used to store multiple elements. Similar to List and Tuple, Set is also a built-in data structure.

In Python, there are many key properties of Sets. Some of these properties are similar to List & Tuple and some of them are very different.

Lets see some key properties of Set in Python.

Properties of Set in Python

  • Set is an unordered collection datatype. Unlike List and Tuple, elements in Set are not stored based on their index positions.
  • Sets can store heterogeneous elements i.e sets can store elements of different datatypes including the collection elements except List. Set does not allow storing List as an element.
  • Set is iterable collection. We can iterate through the elements in Set. But, there is no order defined for elements in Set. During iteration elements can come in any order.
  • Set is mutable collection datatype. It means we can perform add (append), update (change), delete (remove) operations on the set objects.
  • Set does not allow mutable elements to be stored. It means we can store only immutable elements like tuple into the set.
  • Set does not allow duplicate elements. Sets will always store unique elements. But we can store different case-sensitive elements in it. Elimination of duplicate elements from a collection is the primary use case of Set.
  • Set in Python support mathematical operations like union, intersection, difference, and symmetric difference, subset and super-set.

Now, lets see different methods to create Set objects in Python.

Create Set in Python

Set in Python can be declared and initialized using either curly brackets {} or the set() constructor.

Create empty set

To create an empty set we cannot use curly brackets {}. Because curly brackets {} also represent Dictionary collection in Python. By default, empty curly brackets {} will create a Dictionary object.

To create an empty Set, we can use set() constructor.

# empty set creation with set constructor
print("empty set creation with set constructor")
empty_set = set()							# empty set
print(empty_set)
print(type(empty_set))

Output

empty set creation with set constructor
set()
<class 'set'>

From the output, an empty set was create and printed with empty value. In Python, Set class is <class ‘set’>

Create set with Curly Brackets {}

We can use curly brackets {} with elements to create Set. This is straightforward and more common method to create Set.

# set creation with curly brackets
print("set creation with curly brackets")
boolean_set = {True, False, True, True}				# set of boolean
print(boolean_set)
print(type(boolean_set))

print("\n---------------------------------------------------\n")

# set creation with curly brackets
print("set creation with curly brackets")
string_set = {'Python','Java','AWS','Azure'}		            # set of string
print(string_set)
print(type(string_set))

We are using curly brackets {} to create boolean_set with boolean elements and ‘string_set’ with string elements.

Output

set creation with curly brackets
{False, True}
<class 'set'>
---------------------------------------------------
set creation with curly brackets
{'AWS', 'Python', 'Azure', 'Java'}
<class 'set'>

Boolean set was created with two elements in it, duplicate elements were removed. Boolean and string Set elements are printed within curly brackets {} and with class type of <class 'set'>.

Create set from list and tuple

Set can be create using set() constructor using the elements from List or Tuple.

# set creation with set constructor
print("set creation with set constructor")
set_from_list = set(['Python','Java','AWS','Azure'])	# set from list with set constructor
print(set_from_list)
print(type(set_from_list))

set_from_tuple = set(('Python','Java','AWS','Azure'))	# set from tuple with set constructor
print(set_from_tuple)
print(type(set_from_tuple))

First, we are using the set() constructor with List elements to create Set object referenced by variable ‘set_from_list’. Second, we are using the set() constructor with Tuple elements to create Set object referenced by variable ‘set_from_tuple’.

Output

set creation with set constructor
{'Java', 'Azure', 'AWS', 'Python'}
<class 'set'>
{'Java', 'Azure', 'AWS', 'Python'}
<class 'set'>

From the output, elements of Set created from List and Tuple are printed and class type of <class 'set'>.

Set – handling duplicate elements

Set does not allow duplicate elements. Sets will always store unique elements. But we can store different case-sensitive elements in it. Elimination of duplicate elements from a collection is the primary use case of Set.

# set not allows duplicate elements
print("set not allows duplicate elements")
no_duplicate_set = {"Python","Java","AWS","Azure","AWS", "aws"}
print(no_duplicate_set)
print(type(no_duplicate_set))

Here, we are creating a set with curly brackets {}. Elements passed to create a set has duplicate values. ‘AWS’ (in capital letters) is passed two times and ‘aws’ (in small case letters) is also passed. Equality check of elements is case-sensitive. So, elements with small case letter will be different from elements with capital case letters.

Output

set not allows duplicate elements
{'AWS', 'Azure', 'Python', 'aws', 'Java'}
<class 'set'>

In the output, one element ‘AWS’ with capital letters and one element ‘aws’ with small case letters exists. Duplicate elements of ‘AWS’ has been removed.

Copy set from another set

Set can be created as a copy of another set. Set has built-in function copy() to create a copy from another set.

# copy set to create another set
print("copy set to create another set");

shbytes = {"Java","Azure","AWS","Python"}
print(shbytes)

courses = shbytes.copy()             # create set copy of shbytes set
print(courses)

We have Set referenced by a variable name ‘shbytes’. On this set, we are calling copy() function to create another set ‘courses’. Both Sets elements are independently stored and do not reference the same elements. It means, if we made changes to one Set elements it will not auto reflect those changes to the copied set.

Output

copy set to create another set
{'Python', 'Azure', 'AWS', 'Java'}
{'Python', 'Azure', 'AWS', 'Java'}

As shown from output, both Sets has same elements.

Create Frozen Set

Frozen Set is another collection datatype in Python. Frozen Set is immutable datatype, but Set is mutable datatype. It means we cannot perform add (append), update (change), delete (remove) operations on the Frozen Set objects. All other properties of Frozen Set is similar to Set.

Frozen Set is created using frozenset() constructor.

# frozenset with frozenset constructor
print("frozenset with frozenset constructor")
frozen_set = frozenset(["Python","Java","AWS","Azure"])
print(frozen_set)
print(type(frozen_set))

Output

frozenset with frozenset constructor
frozenset({'Java', 'Azure', 'AWS', 'Python'})
<class 'frozenset'>

Frozen Set is create and its elements are printed. It has class type of <class 'frozenset'>.

Access Set elements

Sets are unordered collection datatype. Elements in Set are not stored based on their index positions. Since, there is no indexing of elements in Set, we cannot use index to access the elements from a set.

Elements in Set are accessed directly through loop and in clause. Being unordered, the order of elements in Set is not fixed. While accessing elements from a Set, every time elements of Set can come in different order. Using in and not in clause, we can also check if an element exists in Set or not.

# access element with for loop
print("access element with for loop");

shbytes = {"Java","Azure","AWS","Python"}
print(shbytes)

for course in shbytes:           # access set elements via 'for' loop
	print(course)

print("\n---------------------------------------------------\n")

# check for an element in a set
print("check for an element in a set");
print("AWS" in shbytes)        # check if element exists in Set
print("AWS" not in shbytes)        # check if element exists in Set

Output

access element with for loop
{'AWS', 'Python', 'Java', 'Azure'}
AWS
Python                    # each element of is printed
Java
Azure
---------------------------------------------------
check for an element in a set
True                      # check for element exists in Set
False                    # check for element not exists in Set

Summary

In this article we learn about various scenarios to create Set in Python.

Code – Github Repository

All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.

Python Topics


Interview Questions & Answers

Q: What happens if we try to create a set with mutable elements like lists or dictionaries?

Python sets can only contain immutable (hashable) elements. If we try to create a set with mutable elements like lists or dictionaries, Python will raise a TypeError.

mutable_element_set = {1, 2, [3, 4]} => This raises an error => TypeError: unhashable type: 'list'

Q: How can we convert a list or a tuple into a set?

We can convert a list or a tuple into a set using the set() constructor. This conversion will automatically remove any duplicate elements.

course_list = ['Python','Java','AWS','Azure']
course_set = set(course_list)     # convert list into a set
print(course_set)    # Elements in course_set => {'Azure', 'Java', 'Python', 'AWS'}

course_tuple = ('Python','Java','AWS','Azure')
course_set = set(course_tuple)     # convert tuple into a set
print(course_set)   # Elements in course_set => {'Azure', 'Java', 'Python', 'AWS'}

Q: Explain the time complexity of creating a set from a list of elements.

Time complexity of creating a set from a list of elements is O(n), where n is the number of elements in the list. Python iterate over each element of the list and insert it into the set.

Set has underlying hash table structure, that is why time complexity for insertion of an element into a set is O(1).

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *