In Python, how do I add all the elements of a list to a set?

Question:

I’m using Python 3.7 with Django. How do I create a set and then add all fo the elements from a list into the set? I tried this

result = {}
qset = Article.objects.filter(reduce(operator.or_, (Q(title__icontains=x) for x in long_words)))
result.extend(list(qset))

but I got the error

AttributeError: 'dict' object has no attribute 'append'

on the line

result.extend(list(qset))
Asked By: Dave

||

Answers:

You can use

new_var = set(list_var)

If you want to do it iteratively you can use:

set_var = set()
for item in iterable:
    set_var.add(item)
Answered By: griffin_cosgrove

Analogs of list’s append and extend methods for sets are add and update.

>>> s = set()
>>> s.add(10)
>>> s
{10}
>>> s.update([20, 30, 40])
>>> s
{40, 10, 20, 30}

Argument of update can be not only list, any iterable object: set, tuple, generator, etc. Using this method is (I guess) a little bit faster than adding elements one by one in a loop.

Answered By: lesnik
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.