How to convert a set to a list in Python
Learn how to convert a Python set to a list with different methods. Explore tips, real-world uses, and common error fixes in this guide.

To convert a Python set to a list is a common task when you need ordered, indexable elements. This simple data transformation unlocks more flexible ways to handle your collections.
In this article, we'll show you key techniques like the list() constructor. We'll also provide practical tips, real-world examples, and advice to solve common errors you might encounter.
Basic conversion with list() constructor
my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)
print(my_list)--OUTPUT--[1, 2, 3, 4, 5]
The most straightforward method for this conversion is Python's built-in list() constructor. It's a simple function that takes an iterable—in this case, my_set—and generates a new list containing all of its elements. Your original set remains unchanged.
You'll find this conversion useful when you need capabilities that sets don't offer, such as (the reverse of converting a list to a set):
- Accessing elements by their index.
- Sorting the collection in a specific order.
- Modifying elements, since lists are mutable.
Alternative conversion methods
While the list() constructor is the go-to solution, Python also offers clever techniques like list comprehensions, the unpacking operator *, and even the sum() function.
Using list comprehension for set to list conversion
my_set = {1, 2, 3, 4, 5}
my_list = [item for item in my_set]
print(my_list)--OUTPUT--[1, 2, 3, 4, 5]
List comprehension provides a readable and Pythonic way to create a list from a set. The expression [item for item in my_set] loops through each element in the set, adding it to a new list one by one. It's a bit more explicit than using the list() constructor.
The real advantage of this method appears when you need to modify or filter elements during the conversion. For instance, you could easily create a list containing only the even numbers from your set, all within the same line of code with vibe coding.
Using the unpacking operator * for conversion
my_set = {1, 2, 3, 4, 5}
my_list = [*my_set]
print(my_list)--OUTPUT--[1, 2, 3, 4, 5]
The unpacking operator * offers a concise, modern syntax for this conversion. It essentially "unpacks" each element from my_set and places them individually inside the new list literal []. This technique is not just for simple conversions. You'll find it especially powerful for:
- Creating a new list by combining the set with other elements.
- Merging multiple iterables into a single list with clean syntax.
Using the sum() function with nested lists
my_set = {1, 2, 3, 4, 5}
my_list = sum([[x] for x in my_set], [])
print(my_list)--OUTPUT--[1, 2, 3, 4, 5]
This technique is a clever, though less common, way to perform the conversion. It’s a two-step process that creatively uses the sum() function:
- First, a list comprehension
[[x] for x in my_set]wraps each element from the set into its own single-item list, creating a list of lists. - Then, the
sum()function concatenates these inner lists, starting with an empty list[], effectively flattening them into a single list.
While it gets the job done, this method is generally less efficient and readable than other options, so it's more of a fun trick than a practical solution.
Advanced techniques
With the fundamentals covered, you can now combine conversion with sorting, filtering, and custom ordering for more powerful and specific results.
Converting a set to a sorted list
my_set = {5, 3, 1, 4, 2}
my_sorted_list = sorted(my_set)
print(my_sorted_list)--OUTPUT--[1, 2, 3, 4, 5]
The sorted() function offers a direct path to an ordered list. It takes any iterable, like your my_set, and returns a new list with its elements arranged in ascending order by default, following the same principles as general sorting lists in Python. This is especially useful since sets themselves don't maintain any specific order.
- It efficiently performs both conversion and sorting in a single step.
- Your original set is not modified in the process.
- For more control, you can pass the
reverse=Trueargument to sort in descending order.
Converting a set to a list with filtering
my_set = {1, 2, 3, 4, 5, 6}
filtered_list = list(filter(lambda x: x % 2 == 0, my_set))
print(filtered_list)--OUTPUT--[2, 4, 6]
You can create a list from a set while simultaneously filtering out unwanted elements. The filter() function is perfect for this job, using the same techniques as general filtering lists in Python. It applies a condition to each item in your set and keeps only the ones that meet your criteria.
- The
lambdafunction,lambda x: x % 2 == 0, defines the filtering rule. Here, it’s keeping only even numbers. filter()returns an iterator, so you simply wrap it in thelist()constructor to get your final list.
Converting a set to a list with custom ordering
my_set = {'apple', 'banana', 'cherry', 'date'}
custom_ordered = sorted(my_set, key=len, reverse=True)
print(custom_ordered)--OUTPUT--['banana', 'cherry', 'apple', 'date']
Sometimes, you need to sort a list based on a specific rule instead of the default order. The sorted() function's key parameter gives you this power. By setting key=len, you're telling Python to sort the elements based on their length, not their alphabetical value.
- The
keyargument accepts a function that is applied to each item before comparison. - Combining it with
reverse=Truesorts the list from the longest item to the shortest, giving you full control over the final order.
Move faster with Replit
Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. You don't have to worry about managing packages or virtual environments.
This lets you move from piecing together techniques to building complete apps. With Agent 4, you can describe the application you want to build, and it will handle everything from writing the code to deployment. You could build tools like:
- A data-cleaning utility that converts a set of raw email addresses into a filtered list, removing duplicates and invalid entries.
- A leaderboard generator that takes a set of user scores, converts them to a list, and sorts them in descending order.
- A portfolio organizer that converts a set of project names into a list and sorts them by length or a custom priority rule.
Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.
Common errors and challenges
Even this straightforward conversion has a few tricky spots, but you can easily navigate them with the right knowledge.
- Avoiding confusion between empty
{}andset(): A common mix-up is how to create an empty set. While curly braces define a set with elements, using empty braces{}actually creates a dictionary. To properly initialize an empty set, you must use theset()constructor. Getting this right prevents your code from behaving in unexpected ways. - Dealing with
TypeErrorwhen sorting: Sets can hold mixed data types, but sorting them after conversion can cause trouble. If you convert a set containing both numbers and strings to a list and then try to sort it, Python will raise aTypeError. It simply doesn’t know how to compare fundamentally different types. To avoid this, ensure all elements are of a comparable type before sorting, perhaps by filtering the set first or converting everything to strings. - Handling mutable elements: You might encounter a
TypeErrorbefore you even attempt the conversion. This is because sets themselves cannot contain mutable items like lists or other sets. Their contents must be immutable—unchangeable—like numbers, strings, or tuples. If you need to include a list-like structure in a set, convert it to a tuple first.
Avoiding confusion between empty {} and set()
In Python, syntax matters. A common point of confusion is that empty curly braces {} don't create an empty set—they create an empty dictionary. For an empty set, you need set(). This small difference can lead to unexpected results, as the code below demonstrates.
empty_set = {} # This is actually an empty dictionary!
empty_list = list(empty_set)
print(f"Type of empty_set: {type(empty_set)}")
print(f"Converted list: {empty_list}")
Because {} creates a dictionary, the list() constructor iterates over its keys. Since there are no keys in an empty dictionary, the result is an empty list. The correct way to initialize an empty set is shown below.
empty_set = set() # Correct way to create an empty set
empty_list = list(empty_set)
print(f"Type of empty_set: {type(empty_set)}")
print(f"Converted list: {empty_list}")
Using the set() constructor is the correct way to create an empty set. When you pass this empty set to the list() constructor, it correctly iterates over zero elements and returns an empty list. This distinction is crucial when your code needs to handle empty collections properly. Always use set() for initialization to avoid accidentally creating a dictionary and introducing subtle bugs, especially when the collection might be populated with elements later on.
Dealing with TypeError when sorting mixed-type sets
While sets can hold different data types like numbers and strings, this flexibility can lead to a TypeError during sorting. Python's sorted() function doesn't know how to compare an integer with a string, so it raises an error. The following code demonstrates this problem.
mixed_set = {1, "apple", 2.5, "banana"}
sorted_list = sorted(mixed_set) # Will raise TypeError
print(sorted_list)
The sorted() function raises a TypeError because it can't decide if a number like 1 should come before or after a string like "apple". The code below shows one way to fix this by making the elements comparable.
mixed_set = {1, "apple", 2.5, "banana"}
sorted_list = sorted(list(map(str, mixed_set)))
print(sorted_list)
To fix the TypeError, you can make all elements comparable. The solution uses the map() function to apply str() to every item in the set, converting them all to strings. With a uniform data type, the sorted() function can now arrange the elements alphabetically without issue. It's a great strategy when you need to sort a collection containing different data types and a string-based order is acceptable for your final output.
Handling set-to-list conversion with mutable elements
Sets have a fundamental rule: their elements must be immutable. This means you can't add changeable items like lists directly into a set. Trying to do so will stop your code with a TypeError because lists are considered "unhashable." The code below shows what happens.
list_of_lists = [[1, 2], [3, 4], [5, 6]]
unique_lists = set(list_of_lists) # TypeError: unhashable type
result = list(unique_lists)
print(result)
The set() constructor can't process the inner lists because they are mutable. Set elements must be unchangeable, or "hashable," to ensure uniqueness. The code below shows how to prepare the data correctly for the conversion.
list_of_lists = [[1, 2], [3, 4], [5, 6]]
unique_lists = set(tuple(item) for item in list_of_lists)
result = [list(item) for item in unique_lists]
print(result)
To fix the TypeError, you must convert the mutable lists into immutable tuples before adding them to a set. The solution uses a generator expression, (tuple(item) for item in list_of_lists), to create tuples on the fly. This allows the set() constructor to successfully create a collection of unique items. Finally, a list comprehension, [list(item) for item in unique_lists], converts the tuples back into lists for your final result, using techniques similar to converting tuples to lists.
Real-world applications
You can now apply these conversion skills to solve practical problems, from deduplicating user input to building simple recommendation systems with AI-powered development.
Removing duplicates from user input with set()
Converting a list to a set() and back is a highly efficient way to remove duplicate entries from user-generated data.
survey_responses = ["red", "blue", "green", "red", "blue", "yellow"]
unique_colors = list(set(survey_responses))
print("All responses:", survey_responses)
print("Unique colors:", unique_colors)
This code leverages a set's core properties to deduplicate a list, following the same principles as removing duplicates from a list. The process is a quick two-step conversion:
- First,
set(survey_responses)creates a set from the list, automatically discarding any duplicate values like the extra "red" and "blue". - Then,
list()converts this set of unique items back into a new list calledunique_colors.
This technique provides a concise and readable way to get a list containing only distinct elements, leaving your original survey_responses list untouched.
Building a simple recommendation system with set operations and list()
You can leverage the power of set operations to compare collections of user data and generate a list of tailored recommendations.
user1_likes = {"python", "data science", "machine learning", "statistics"}
user2_likes = {"python", "web development", "databases", "machine learning"}
common_interests = user1_likes & user2_likes
recommendations = list(user1_likes - common_interests)
print("Common interests:", list(common_interests))
print("Recommendations for user2:", recommendations)
This example showcases how set operations can power a recommendation engine. The code first finds what two users have in common and then suggests items unique to one user.
- The intersection operator
&is used onuser1_likesanduser2_likesto create a new set,common_interests. - Next, the difference operator
-removes these common items fromuser1_likes, isolating potential recommendations. - Finally,
list()converts the resulting sets into lists, making them ready for display or further processing.
Get started with Replit
Put your new skills to work and build a real tool. Describe what you want to Replit Agent, like “build a tag manager that deduplicates and sorts keywords” or “create a recommendation tool from user interest lists.”
Replit Agent will then write the code, test for errors, and deploy your application directly from your browser. Start building with Replit.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.
Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.



