How to create a set in Python

What is a set

A set is an unordered collection with no duplicate elements.

We can create a set from a range.


print set(range(10)) 

The code above generates the following result.

Or we can create a set from a list.


print set([0, 1, 2, 3, 0, 1, 2, 3, 4, 5]) 

The code above generates the following result.

Sets are constructed from a sequence or some other iterable object. Their main use lies in checking membership, and thus duplicates are ignored.

Set operations


a = set('abracadabra')
b = set('alacazam')
print a                                  # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
print a - b                              # letters in a but not in b
# from  w w w.  j  a  v a 2  s  . c  o m
print a | b                              # letters in either a or b

print a & b                              # letters in both a and b

print a ^ b                              # letters in a or b but not both

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary