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

securecoding picture securecoding · Apr 2, 2013 · Viewed 424.3k times · Source

I have a list of filenames in python and I would want to construct a set out of all the filenames.

filelist=[]
for filename in filelist:
    set(filename)

This does not seem to work. How can do this?

Answer

mgilson picture mgilson · Apr 2, 2013

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! (Isn't duck typing great?)


If you want to do it iteratively:

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

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