How to Convert an Iterable to a Set in Python

πŸ’‘ Problem Formulation: In Python, you may often need to convert an iterable, such as a list or a tuple, into a set. This is particularly useful when you want to eliminate duplicate elements and unorder the collection.

Suppose you have a list ['apple', 'banana', 'apple', 'orange'] and you want to convert it into a set so that each element is unique, resulting in {'apple', 'banana', 'orange'}.

Method 1: Using the set() constructor

The most straightforward method to convert an iterable to a set in Python is to use the set constructor, set(). This built-in function takes an iterable as an argument and returns a new set object containing all the distinct elements.

Here’s an example:

fruits_list = ['apple', 'banana', 'apple', 'orange']
fruits_set = set(fruits_list)
print(fruits_set)

Output:

{'banana', 'orange', 'apple'}

This code snippet transforms the fruits_list into a set called fruits_set by passing it to the set() constructor. Since sets automatically remove duplicates, ‘apple’ appears only once in the output.

πŸ‘‰ Python Create Set From 1 to N

Method 2: Set comprehension

Set comprehension is a concise way to convert an iterable into a set. It is similar to list comprehension but with curly braces. This method also allows for the inclusion of conditional statements to filter out certain elements.

Here’s an example:

fruits_list = ['apple', 'banana', 'apple', 'orange']
fruits_set = {fruit for fruit in fruits_list if fruit != 'banana'}
print(fruits_set)

Output:

{'orange', 'apple'}

In this example, set comprehension is used to create fruits_set from fruits_list by iterating over each element. The conditional statement excludes ‘banana’ from the resulting set, showcasing the flexibility of set comprehensions for filtering.

πŸ‘‰ How to Create a Python Set of Size n?

Method 3: Using the map function

The map() function can be applied in combination with the set constructor to convert each element of the iterable to a set, which can be useful if a transformation function is required during conversion.

Here’s an example:

fruits_list = ['apple', 'banana', 'cherry']
fruits_set = set(map(str.upper, fruits_list))
print(fruits_set)

Output:

{'BANANA', 'APPLE', 'CHERRY'}

With this approach, map() applies the str.upper method to each element of fruits_list. The resulting uppercase strings are then turned into a set by the set constructor, demonstrating a conversion with modification.

Method 4: Using union() on an empty set

Another way to create a set from an iterable is to use the union() method, which combines the elements of the iterable with those of another set. Using union() on an empty set with the iterable as an argument will yield a set with the elements of the iterable.

Here’s an example:

fruits_list = ['apple', 'banana', 'orange']
fruits_set = set().union(fruits_list)
print(fruits_set)

Output:

{'banana', 'orange', 'apple'}

This code leverages the union() method on an empty set to include all elements from fruits_list, thereby converting it to a set without any added complexity.

πŸ‘‰ Convert List to Tuple | The Most Pythonic Way

Bonus One-Liner Method 5: Using the {*iterable} syntax

A quick one-liner method akin to set comprehension is to use the {*iterable} syntax. It is essentially an unpacking operator that can unpack the elements of an iterable into a new set.

Here’s an example:

fruits_list = ['apple', 'banana', 'orange']
fruits_set = {*fruits_list}
print(fruits_set)

Output:

{'banana', 'orange', 'apple'}

This concise snippet unpacks fruits_list into a set called fruits_set by using the unpacking operator *, which is another elegant way to convert an iterable to a set.

Summary/Discussion

  • Method 1: Using the set() constructor. Strengths: Simple and direct. Weaknesses: Does not allow element transformation during conversion.
  • Method 2: Set comprehension. Strengths: Offers filtering and transformation capabilities. Weaknesses: Slightly more complex syntax.
  • Method 3: Using the map function. Strengths: Useful for applying a function to elements during conversion. Weaknesses: Not as direct for simple conversions.
  • Method 4: Using union() on an empty set. Strengths: Familiar for users who work with set operations. Weaknesses: More verbose and slightly less efficient than using the set constructor.
  • Method 5: Using the {*iterable} syntax. Strengths: Extremely concise for simple unpacking into a set. Weaknesses: Less known and might be confusing for beginners.

πŸ‘‰ A Simple Introduction to Set Comprehension in Python

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!