securecoding securecoding - 1 year ago 63
Python Question

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

I have a

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

for filename in filelist:

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

Answer Source

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

lst = ['', '', '', '', 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:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download