Python 2.7 – Fundamentals – Collections – Sets

A set is an unordered collection of mixed data types. No duplicates can be there in a set. Sets are declared by enclosing the items in curly brackets with each item separated by a comma.


The following operators work on sets

  • in – membership
  • len – length
  • | – or
  • & – and
  •  – – minus
  • <= – equivalence

They are examined in detail below:

in – membership

Checks if an item exists in the set

len – length of set

Returns the length of a set. If set has no items then the length is zero

 | – logical or set1 | set2

Combines items of set1 and set2 to create a new set with all the elements of both the sets. Duplicates are ignored

& – logical and set1 & set2

Combines items of set1 and set2 to create a new set with only the common elements in both the sets

 – minus  set1 – set2

Returns all the items in set1 which are not in set2

<= equivalence set1 <= set2

Checks whether all items in set1 are in set2









Sets also support methods which are the same as their mathematical counterparts, which are shown below:

  • union
  • intersection
  • difference
  • issubset
  • add
  • remove
  • pop
  • clear

union – set1.union(set2)

Returns elements from both set1 and set2. Duplicates are ignored

intersection – set1.intersection(set1)

Returns only common elements from both set1 and set2.

difference – set1.difference(set2)

Returns elements in set1 which are not in set2.

issubset – set1.issubset(set2)

Returns True if all elements of set1 are in set2, else False

add – set1.add(item)

Adds an item to a set. If an item already exists it is not added

remove – set1.remove(item)

Removes an item from the set. If item does not exist then an error is thrown

pop – set1.pop()

Removes an arbitrary item from the set. Since a set is not ordered, there is no guarantee on which item will be removed

clear – set1.clear()

Removes all the elements from a set











The last collection we will look at are dictionaries.

1 Trackback / Pingback

  1. Python 2.7 – Fundamentals – Collections – Tuples – Truelogic Blog

Leave a Reply

Your email address will not be published.