The best data structure for storing non-duplicate items in Python while ensuring each item is unique (i.e., duplicates are automatically removed) is the set
data structure.
A set is an unordered collection of unique elements, meaning it cannot contain any duplicate items. When you add elements to a set, Python automatically removes any duplicates. This makes it a perfect choice for scenarios where you need to store a collection of items while ensuring uniqueness.
You can create a set in Python using curly braces {}
or the built-in set()
function. Here's an example:
# Creating a set
my_set = {1, 2, 3, 4, 3, 5} # Duplicate '3' is automatically removed
print(my_set) # Output: {1, 2, 3, 4, 5}
If you have a list with potential duplicates and want to remove them to create a set, you can simply convert the list to a set using the set()
function:
# Removing duplicates from a list and creating a set
my_list = [1, 2, 2, 3, 4, 4, 5]
my_set = set(my_list)
print(my_set) # Output: {1, 2, 3, 4, 5}
Sets provide fast membership testing and efficient operations for set theory operations (e.g., union, intersection, difference), which makes them a great choice for handling collections of unique elements in Python.
🎥 Video Tutorial
If you like to watch a video guideline, then I have also created a video just for you!
Conclusion
I hope you have enjoyed this short article.
If you have any questions then please let me know by reaching out on Twitter or LinkedIn.
You can also follow me on:
🎁GitHub: FahimFBA
🎁YouTube: @FahimAmin
If you are interested then you can also check my website: https://fahimbinamin.com/