Courses Enquiry

# Python Sets

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

Unlock learning opportunities with our expert-led coding courses.
Real-time doubt solving in a live online coding class is also available in the course
that will help you to stay connected with an experts while learning.

Browse Online Coding Classes Videos