manyspikes

Sets

Initialising environment...

Sometimes you may want to store a collection of elements, but you are not particularly interested in their order and/or you don't want to store duplicated elements. In such cases, you can use a set. Sets are defined by enclosing a sequence of comma-separated values within curly brackets, {...}.

x = {1, 5, 3}

A few things to note:

  • Sets are mutable. For instance, you can add the value 2 to a set x by using x.add(2)
  • Because they are unordered, sets do not support indexing or slicing
  • Sets can only contain values that are hashable (we will cover this later). Typically that means that all values in a set must be immutable. This allows us to search for an object very efficiently.

Sets are often used for checking if a value is present in a set (membership testing) or for removing duplicates in lists

x_list = [1, 4, 1, 2, 3, 3] x_set = set(x_list) print(x_set) print(0 in x_set)

The set function above converts the list x_list into a set, and thereby removes its duplicate values. The code above would print:

{1, 2, 3, 4}
False

Note: In lists, membership testing using the in operator requires the program to check the value of every element of the list, so if your list is very large this can be quite inefficient. Using sets, the program is able to test for membership in constant time, irrespectively of how large your set is.

Instructions

The code below aims to create a set containing the number of times you have visited different european capitals. Each element of the set is a sequence, where its first element represents the name of the city as a string and the second element represents the number of tiemes you have visited that city.

trips = {["Madrid", 1], ["Berlin", 7], ["Paris", 3], ["London", 5]}

However, the code above raises an error as the set cannot be created. Can you spot what the problem is?

Copy and past the snippet to the answer window and ammend it so that the set can be successfully created.