Skip to content

Python Sets overview with Create & Add Set Examples

  • by

Python sets are an unordered collection of items. In a set, all elements (items) are unique (no duplicates) and must be immutable (not changeable) but the set as a whole is mutable. You can create a set by placing all the items inside curly braces { } and separated by comma or by using the built-in function set().

Python Sets overview with Create & Add Set Examples

What type of items (variable type) can be in the Python set?

Set can have any number of different types like – integer, float, tuple, strings, etc. One more thing set can’t have mutable elements.

You can perform standard operations on sets (union, intersection, difference) like mathematics.

Python sets syntax :

Here is the simple syntax of sets in python.

set = {"item1", "item2" , ....}

How to define Python sets :

It’s a simple example of creating a set, where all duplicates elements removed by python.

set1 = {1, 2, 3, 6, 1, 2}
set2 = {"java", "python", "android", "java"}
print(set1)
print(set2)

Output : {1, 2, 3, 6}

{‘android’, ‘python’, ‘java’}

Accessing Values in a Set

You can’t access individual items from a set. If you want you can use the loop through the set. Let’s see an example with for loop.

set1 = {1, 2, 3, 6, 1, 2}
for s in set1:
    print(s)

Output: 1
2
3
6

Add item in The Sets

You can add an item in a Set using add() in the build method. There is no specific indexing for the new element.

set2 = {"java", "python", "android", "java"}
set2.add("ruby")
print(set2)

Output : {‘android’, ‘java’, ‘ruby’, ‘python’}

Remove item in The Sets

You can remove elements from a set by using discard() method. Check this removing item from python sets an example.

set2 = {"java", "python", "android", "java"}
set2.discard("java")
print(set2)

Output : {‘android’, ‘python’}

Get The Length of sets 

You have to use the len() method to return the number of items, check this example.

set2 = {"java", "python", "android", "java"}
print(len(set2))

Output : 3

Do comment if any doubt or a suggestion or code to help others.

Note : This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Python sets Examples are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

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