Data Structures - Set

Set is a collection that holds items (of different types). Set is unordered and changeable collection of unique elements.

  • Mutable - the programmer can edit the set after its creation - removing or adding items .
  • Unordered - means that the order of the items can change.

A single value can't be stored twice in a set - every item is unique.
A Set can be created by placing the items inside curly brackets {item1, item2}, and separating the items with a comma.

Here is an example:

#Creating a set my_set = {3, 2, 7, "tutorial", "computer"} print(my_set) type(my_set)

Access Items

Set doesn't support indexing and therefore it is not possible to access items the same way like other datatypes. However, it is possible to iterate through the items (watch the data-flow tutorials).

#Set my_set = {3, 2, 7, "tutorial", "computer"} for item in my_set: print(item) print(type(my_set)) print(my_set[2])

In the last example above, we try to access an item using an index. Set doesn't support indexing - an error is raised.

Sets - Functions and Methods

Len

The len() function returns the length of a set.

#len() our_set = {"java", "python", "c++"} print(len(our_set)) print(len(our_set) / 2)

Add

Using the add() method we can add an item

#add() our_set = {"java", "python", "c++"} print(our_set) our_set.add("php") print(our_set)

Discard

Using the discard() method we can remove items. Error isn't raised if the item doesn't exist.

#discard() our_set = {"java", "python", "c++"} print(our_set) our_set.discard("java") print(our_set) our_set.discard("java") print(our_set)

Difference

Using the difference() method we inspect the differences between sets.

#difference() our_set = {"java", "python", "c++"} their_set = {"java", "php"} dif_set = our_set.difference(their_set) print(dif_set)

Exercise 1

Create a set and print it out

#Create a set #Print

Exercise 2

  1. Create a set.
  2. Add as many items as you wish.
  3. Remove one of the items.
  4. Create another set.
  5. Print the differences.
  6. Print the differences of the length of the sets.

#Create a set #Add items #Remove an item #Create a set #Print the differences #Print the differences of the length