In today’s tutorial, we will learn how to convert an array to a set in Python. Python consists of several data structures that store collections of data, and among these are arrays and sets.
The collections are different in the way they store and handle their data. While an array is a list that can store a series of items of the same type, a set is a collection of unique items and does not keep items in a specific order.
This is an incredibly useful and common operation when working with data in Python.
Step 1: Define an Array
Firstly, let’s define an array. In Python, we usually use lists as arrays:
arr = ['Python', 'Java', 'C++', 'Python', 'Java', 'Python']
Here we have defined an array, ‘arr’, with duplicate items.
Step 2: Use Python’s Built-In ‘set’ function
Python’s set function can be used to convert an array to a set. Here is how:
set_arr = set(arr)
This transforms our array into a set, removing any duplicate elements in the process.
Step 3: Print the Set
Now that we have converted our array to a set, we can print it out to confirm that the conversion was successful.
print(set_arr)
Full Code
Here is the complete Python code we used:
arr = ['Python', 'Java', 'C++', 'Python', 'Java', 'Python'] set_arr = set(arr) print(set_arr)
Code Output
Now let’s discuss the output of the code:
{'Java', 'C++', 'Python'}
The output is a set of unique items from the array. ‘Python’ and ‘Java’ were each listed multiple times in our original array, but in our set, each appears only once.
Conclusion
Converting an array to a set in Python couldn’t be easier! With just a few lines of code, we can transform an array into a set, effectively removing any duplicates. Python’s set function is just one of its many built-in functions that provide powerful functionality right out of the box.