How to Convert Array to Set in Python?

Recently, in a webinar, someone asked how to convert an array to a set in Python. So I decided to write an article on various methods to achieve this. Let us explore more about this topic with some real-world examples and screenshots of executed example codes.

Why Convert an Array to a Set in Python?

Before getting into the methods, let us discuss why you might want to convert an array to a set. Sets in Python are collections that are unordered, mutable, and do not allow duplicate elements. This makes sets useful:

  • Removing duplicate values: If you have an array with repeated elements, converting it to a set will automatically remove duplicates.
  • Membership testing: Sets provide a highly efficient way to check for the presence of an element.
  • Set operations: Sets support mathematical operations like union, intersection, difference, and symmetric difference.

Check out How to Count Occurrences in Python Arrays

Convert an Array to a Set in Python

There are various methods to convert an array to a set in Python. Let me show you a few methods with examples.

Method 1: Using the set() Function

The most simple method to convert an array to a set in Python is by using the set() function. This method is efficient and easy to understand.

Example

Imagine you have an array of ZIP codes from different cities in the USA, and you want to remove any duplicates.

zip_codes = [10001, 90210, 30301, 10001, 60601, 90210]
unique_zip_codes = set(zip_codes)
print(unique_zip_codes)

Output:

{10001, 90210, 60601, 30301}

Have a look at the screenshot below to know

Convert Array to Set in Python

As you can see, the duplicate ZIP codes 10001 , 90210 are removed.

Read How to Reshape an Array in Python Using the NumPy Library

Method 2: Using a For Loop

Another way to convert an array to a set is by using a for loop. This method gives you more control over the process and can be useful in more complex situations.

Example

Suppose you have an array of area codes from various states and you want to convert it to a set.

area_codes = [212, 213, 312, 415, 212, 213]
unique_area_codes = set()
for code in area_codes:
    unique_area_codes.add(code)
print(unique_area_codes)

Output:

{312, 212, 213, 415}

Have a look at the screenshot below to know

How to Convert Array to Set in Python

Check out How to Remove the First Element from an Array in Python

Method 3: Using Set Comprehension

Set comprehension is a brief way to create sets in Python. It is similar to list comprehension but produces a set.

Example

Let’s say you have an array of state abbreviations, and you want to convert it to a set.

state_abbreviations = ['NY', 'CA', 'IL', 'TX', 'NY', 'CA']
unique_states = {state for state in state_abbreviations}
print(unique_states)

Output:

{'CA', 'TX', 'IL', 'NY'}

Have a look at the screenshot below to know

Convert Array to Set in Python Using Set Comprehension

Read How to Transpose an Array in Python

Method 4: Using dict.fromkeys()

A less common but interesting method to convert an array to a set is by using dict.fromkeys(). This method leverages the fact that dictionary keys are unique.

Example

Consider an array of city names, and you want to ensure there are no duplicate entries.

cities = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'New York', 'Los Angeles']
unique_cities = set(dict.fromkeys(cities))
print(unique_cities)

Output:

{'Los Angeles', 'New York', 'Chicago', 'Houston'}

Have a look at the screenshot below to know

Convert Array to Set in Python Using Using dict.fromkeys()

Check out How to Find the Number of Elements in a Python Array

Handle Nested Arrays

Sometimes, you might encounter nested arrays (arrays within arrays) and need to convert them to sets. Here’s how you can handle such cases.

Example

Imagine you have an array of arrays, each containing area codes from different states.

nested_area_codes = [[212, 213], [312, 415], [212, 312]]
unique_area_codes = {code for sublist in nested_area_codes for code in sublist}
print(unique_area_codes)

Output:

{312, 212, 213, 415}

Read How to Save an Array to a File in Python

Convert Array to Set in Python – Applications

Removing Duplicates in Large Datasets

In data analysis, you often deal with large datasets that may contain duplicate entries. Converting arrays to sets can help clean your data efficiently.

Example

Suppose you have a large dataset of customer IDs from various states and you want to remove duplicates.

customer_ids = [101, 102, 103, 101, 104, 105, 102, 106]
unique_customer_ids = set(customer_ids)
print(unique_customer_ids)

Output:

{101, 102, 103, 104, 105, 106}

Check out How to Sort an Array in Python

Efficient Membership Testing

Sets provide a fast way to check if an element is present in the collection.

Example

Let’s say you have a list of prohibited items for a flight, and you want to check if any items in a passenger’s luggage are prohibited.

prohibited_items = {'knife', 'gun', 'explosives'}
luggage = ['laptop', 'knife', 'book']
for item in luggage:
    if item in prohibited_items:
        print(f"Prohibited item found: {item}")

Output:

Prohibited item found: knife

Read 3D Arrays in Python

Conclusion

I hope you find this tutorial helpful for understanding the conversion of an array to a set in Python. In the above article, I have explained the various needs of converting an array to a set in Python. We discussed four main methods that are, by using set() Function, using For Loop, using set comprehension, and by dict.fromkeys() along with some applications. Hope you also learned how to handle nested arrays in Python.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.