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))
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)
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 add
ing elements one by one in a loop.
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))
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)
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 add
ing elements one by one in a loop.