Test your Programming knowledge

50% users failed to get the best score. It's your turn to test now.
Questions curated by the expert mentors at codzify.com

Start Quiz

Article

Python Set - Codzify.com

1min 45 sec read

A Python set is an unordered collection of distinct elements. Set is unordered means elements in the set can appear in random order. Sets are written using {} curly brackets.

A set is an unordered collection of items. Every set element is unique (no duplicates) and must be immutable (cannot be changed). However, a set itself is mutable. We can add or remove items from it.

The basic example of Set

#Create a Set languages = {"C", "C++", "Java"} print(type(languages)) print(languages) # Check if an element is a member of the set print("C" in languages) print("Python" in languages) # Add an element in a set languages.add("Python") print(languages) # Remove an element from the set languages.remove("Java") print(languages)

Try to execute the code. You notice elements in the set will be displayed in random order.

Looping through Set

Looping through a set also displays elements in random order. Whereas, looping through lists displays elements in the same order.

Loop through Set

print("*********** Looping throug a Set - Order is NOT maintained - UNORDERED ************") languages = {"C", "C++", "Java"} for indx, x in enumerate(languages): print(indx, x)

Loop through List

print("*********** Looping throug a List - Order is maintained ***************") languages = ["C", "C++", "Java"] for indx, x in enumerate(languages): print("%d %s" % (indx, x))

Set Comprehension

Python Set comprehension allows us to construct the dictionary easily. In this example, we will find the square root of numbers in range 10 using set comprehension.

from math import sqrt print("*********** Set Comprehension - Repeated elements are NOT ALLOWED ************") nums_sqrt_set = {int(sqrt(x)) for x in range(10)} print(nums_sqrt_set)

Using List Comprehension

If we run sample example of finding a square root in range 10 using List Comprehension, you see repeated elements are allowed.

from math import sqrt print("*********** List Comprehension - Repeated elements are ALLOWED ***************") nums_sqrt_list = [int(sqrt(x)) for x in range(10)] print(nums_sqrt_list)

You may notice the difference between List Comprehension and Set Comprehension. Set Comprehension uses {int(sqrt(x)) for x in range(10)} (curly brackets)

Whereas,

List Comprehension uses [int(sqrt(x)) for x in range(10)](square brackets).

Recommended Articles

Did you found this article helpful?

Try to execute what you have learnt

Easy to use online data structure compiler where you can execute the programs in your favourite programming language.
(C, C++, Python)

Open Compiler

HTML, CSS and Javascript Real time Web Editor

Execute your HTML, CSS and javascript code in real time with the web editor
(HTML, CSS, Bootstrap, Javascript)

Open Web Editor