Python Set

Sets in Python

Set is a collection of non-repetitive elements.

S= Set()          # No repetition allowed!

S.add(1)

S.add(2)

# or Set = {1,2}

If you are a programming beginner without much knowledge of mathematical operations on sets, you can simply look at sets in python as data types containing unique values.

Properties of Sets
  1. Sets are unordered # Elements order doesn’t matter
  2. Sets are unindexed # Cannot access elements by index
  3. There is no way to change items in sets
  4. Sets cannot contain duplicate values
Operations on Sets

Consider the following set:

S = {1,8,2,3}

  1. Len(s) : Returns 4, the length of the set
  2. remove(8) : Updates the set S and removes 8 from S
  3. pop() : Removes an arbitrary element from the set and returns the element removed.
  4. clear() : Empties the set S
  5. union({8, 11}) : Returns a new set with all items from both sets. #{1,8,2,3,11}
  6. intersection({8, 11}) : Returns a set which contains only items in both sets. #{8}
Python Set

Exercise : Python Dictionary and Set

  1. Write a program to create a dictionary of Hindi words with values as their English translation. Provide the user with an option to look it up!
  2. Write a program to input eight numbers from the user and display all the unique numbers (once).
  3. Can we have a set with 18(int) and “18”(str) as a value in it?
  4. What will be the length of the following set S:

S = Set()

S.add(20)

S.add(20.0)

S.add(“20”)

What will be the length of S after the above operations?

  1. S = {}, what is the type of S?
  2. Create an empty dictionary. Allow 4 friends to enter their favorite language as values and use keys as their names. Assume that the names are unique.
  3. If the names of 2 friends are the same; what will happen to the program in Program 6?
  4. If the languages of two friends are the same; what will happen to the program in Program 6?
Was this article helpful?
YesNo

Leave a Comment

Your email address will not be published. Required fields are marked *