position: fixed; top: auto !important; margin-left: 112px;

Python Set

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)


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

Previous Next Article


Largest collection of up-to-date tutorials to learn programming languages. We are focused on easy learning. Massive collection of interview questions one may need for preparation.

Social Profile


Copyright 2019. All rights reserved.