Python Sets overview with Create & Add Set Examples

Python sets is 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 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.

How to define Python sets :

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

Output : {1, 2, 3, 6}

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

Accessing Values in a Set

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

Output: 1

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.

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 form python sets an example.

Output : {‘android’, ‘python’}

Get The Length of sets 

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

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.