Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Recap
Using sets to compute unique elements
5. Creating sets with unique element characteristics
Set operations
Simulating machines
Summary

Instruction

Perfect! We can also use sets to store the unique values of a characteristic computed from the elements of a given list. Take a look:

cities = ['London', 'Madrid', 'Milan', 'Bordeaux', 'Milan', 'London', 'Lisbon', 'London']
first_letters = set()
for city in cities:
  first_letters.add(city[0])

In the example above, we want to find all the unique first letters for the elements in the list. Inside a loop, we simply add the first letter of each city to the first_letters set. Because sets only hold unique values, duplicates will be ignored when we invoke first_letters.add(city[0]).

Exercise

We want to manufacture key rings with the car makes found in the people_cars dictionary. The size of each key ring will depend on the number of letters in the car make name. Create the set named car_make_lengths and add all unique car make length values to it. Then, print the following sentence:

There will be {x} different sizes of key rings.

Stuck? Here's a hint!

Iterate over all the values in the dictionary with people_cars.values() and add len(value) to your set.

To get the size of the set, use the len() function.