Open In App

Python Convert Set To List Without Changing Order

Last Updated : 15 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Sets in Python are inherently unordered collections. If the order of the elements is important, the input set must have been created in a specific order, such as by using an ordered iterable like a list. Let us explore different methods to convert a set to a list without changing its apparent order.

Using list constructor

The simplest way to convert a set to a list is by using the list constructor. This method preserves the order in which the set was created.

Python
s = {"Python", "with", "GFG"}

# Convert set to list
res = list(s)
print(res)

Output
['with', 'GFG', 'Python']

Explanation:

  • We pass the set to the list constructor, which creates a new list containing all the elements of the set.
  • The order in the resulting list corresponds to the insertion order of elements in the set.

Let's explore some more methods and see how we can convert set to list without changing it's order.

Using list comprehension

We can also use a list comprehension to explicitly iterate through the set and construct a list.

Python
s = {"Python", "with", "GFG"}

# Convert set to list using list comprehension
result = [item for item in s]
print(result)  

Output
['with', 'Python', 'GFG']

Explanation:

  • List comprehension iterates through each element of the set and adds it to a new list.
  • This method is functionally the same as using the list constructor but provides more flexibility if additional operations are required during the conversion.

Using unpacking

Another concise approach is to use unpacking with square brackets to convert the set into a list.

Python
s = {"Python", "with", "GFG"}

# Convert set to list using unpacking
res = [*s]
print(res)  

Output
['with', 'GFG', 'Python']

Explanation:

  • The unpacking operator * extracts all the elements of the set and places them in a new list.
  • This method is concise and achieves the same result as the previous ones.

Next Article

Similar Reads