How to convert a set to a list in Python

Published on Aug. 22, 2023, 12:16 p.m.

To convert a Python set to a list, you can use the list() function. The list() function takes an iterable as input and returns a new list containing the elements of the iterable. Here’s an example:

my_set = {1, 2, 3, 4, 5}
my_list = list(my_set)

print(my_list)   # Output: [1, 2, 3, 4, 5]

In this example, we define a set my_set containing some elements (from 1 to 5). We use the list() function to convert the set into a list called my_list. The resulting list contains the same elements as the original set.

In general, converting a set to a list can be useful when you need to perform list operations on the elements, such as indexing or sorting. Note that the order in which the elements appear in the resulting list may not be the same as in the original set, since sets are unordered and the order of elements in the list is determined by the order they are returned by the list() function.

Tags:

related content