How to construct a set out of list items in python?

How to construct a set out of list items in python?

If you have a list of hashable objects (filenames would probably be strings, so they should count):

lst = [foo.py, bar.py, baz.py, qux.py, Ellipsis]

you can construct the set directly:

s = set(lst)

In fact, set will work this way with any iterable object! (Isnt duck typing great?)


If you want to do it iteratively:

s = set()
for item in iterable:
    s.add(item)

But theres rarely a need to do it this way. I only mention it because the set.add method is quite useful.

The most direct solution is this:

s = set(filelist)

The issue in your original code is that the values werent being assigned to the set. Heres the fixed-up version of your code:

s = set()
for filename in filelist:
    s.add(filename)
print(s)

How to construct a set out of list items in python?

You can do

my_set = set(my_list)

or, in Python 3,

my_set = {*my_list}

to create a set from a list. Conversely, you can also do

my_list = list(my_set)

or, in Python 3,

my_list = [*my_set]

to create a list from a set.

Just note that the order of the elements in a list is generally lost when converting the list to a set since a set is inherently unordered. (One exception in CPython, though, seems to be if the list consists only of non-negative integers, but I assume this is a consequence of the implementation of sets in CPython and that this behavior can vary between different Python implementations.)

Leave a Reply

Your email address will not be published. Required fields are marked *