### Online Classes

Results can only be achieved if you have the focused direction and crystal clear knowledge. To achieve this, you need a mentor. We will help you out by connecting with an expert mentor in the field.

Learn More

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.

## 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).

## 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