This second article picks up where we left off, moving from lists and tuples to sets and dictionaries. By the end of this article, we should get a resounding answer to my Python instructor's question.
Sets
my_set = {1, 2, (4, 5)}
A set is a collection of unique data; therefore, no element within a set can be duplicated, eg, True
and 1
or False
and 0
.
They are useful in membership testing because they use a hash table under the hood, and to eliminate duplicate entries, eg, storing information about student IDs.
Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Key Features of a Set
- Unordered - elements cannot be accessed in a specific order
- Mutable - elements can be altered after creation.
- No duplicates - elements are all unique.
- Unindexed - items cannot be accessed via indexes.
Common Set Methods
Method | Description |
---|---|
add() |
Adds an element to the set. |
discard() |
Removes an element if present. |
clear() |
Removes all elements. |
copy() |
Returns a shallow copy. |
union() |
Returns the set containing the union of sets. |
intersection() |
Returns a set that is the intersection of two other sets. |
difference() |
Returns a set containing the difference between two or more sets. |
symmetric_difference() |
Returns elements that are in either of the two sets but not in both. |
Similar to list comprehensions, set comprehensions are also supported.
evens = {x for x in range(11) if x % 2 == 0}
print(evens)
Output
{0, 2, 4, 6, 8, 10}
When to use Sets
- When carrying out mathematical set operations upon the data, like union or intersection.
- Membership testing - checking if an element exists within a set, which is faster than using a list or tuple.
- Removing duplicates - sets remove duplicates that can be useful in finding the unique count of items.
- Efficient lookups - as a result of the fast membership testing, sets are useful when checking if an item is present in a collection.
Dictionaries
phonebook = {'Ali': 0712345, 'Maria': 0721435}
A dictionary stores values in key-value pairs. Similar to real-world dictionaries, each word(key) has a definition(value), requiring the keys to be unique within one dictionary.
Key Features of a Dictionary
- Ordered - as of Python version 3.7
- Keys are case sensitive.
- Keys must be unique - duplicate keys are not allowed
- Internally uses hashing - operations can be performed in constant time.
- Mutable - items can be changed, added or removed after the dictionary has been created.
Common Dictionary Methods
Method | Description |
---|---|
pop() |
Removes the item with the specified key. |
clear() |
Removes all items from the dictionary. |
keys() |
Returns all the dictionary's keys. |
values() |
Returns all the dictionary's values. |
items() |
Returns a view object that displays a list of dictionary's key-value tuple pairs. |
get() |
Returns the value of the specified key. |
popitem() |
Removes and returns the last key-value pair. |
When to use a Dictionary
- Fast lookups by unique key. For example, looking up a person's phone number using their name in a contact list.
- When working with data that has a clear mapping. eg, mapping user IDs to the user info.
- When organizing structured data. eg, storing a person's profile with fields like name, age and email.
- When grouping related information together. eg, storing the country name and the capital city.
Comparison of Python Data Structures
Type | Mutable | Ordered | Indexed | Allows Duplicates | Key-Value Pairs | Use Case Example |
---|---|---|---|---|---|---|
list |
✅ | ✅ | ✅ | ✅ | ❌ | Storing a sequence of items (e.g., tasks) |
tuple |
❌ | ✅ | ✅ | ✅ | ❌ | Fixed data (e.g., coordinates, RGB values) |
set |
✅ | ❌ | ❌ | ❌ | ❌ | Unique items collection (e.g., tags) |
dict |
✅ | ✅* | ❌ | ✅ (keys: ❌) | ✅ | Key-value mapping (e.g., user profiles) |
In conclusion, sets are mutable, not '-utable'.
Top comments (1)
A great read for a beginner-friendly introduction to Python.