How to construct a set out of list items in python?
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?
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)
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.