set.update()
Adds every element from one or more lists, sets or other iterables into the set, in place. Duplicates are ignored.
set.update(*others)update() is the many-at-once version of set.add(): it loops over whatever you give it and adds each element. Elements already in the set are ignored.
It changes the set and returns None, just like set.add(). The operator a |= b does the same for two sets. For a new set, leaving the original alone, use set.union().
Because it loops over its argument, a string is added character by character. To add a whole word, use add() or wrap the word in a list.
Parameters
| Parameter | What it is |
|---|---|
*othersoptional | Any number of sets, lists, tuples, strings or other iterables whose elements should be added. |
Return value
Nothing (None). The set is changed in place.
Examples
1Add several elements
nums = {1, 2}
nums.update([2, 3, 4])
print(nums){1, 2, 3, 4}2Collect every tag used in some posts
posts = [["travel", "food"], ["food", "recipes"], ["travel"]]
all_tags = set()
for tags in posts:
all_tags.update(tags)
print(len(all_tags), "tags:", sorted(all_tags))3 tags: ['food', 'recipes', 'travel']
The tags are printed with sorted(), because a set of strings can print in a different order each run.
3Several sources at once
seen = {0}
seen.update({1, 2}, (2, 3), range(4, 6))
print(seen){0, 1, 2, 3, 4, 5}Common mistakes
Updating with a string
A string is split into characters. Put the word in a list, or use add().
words = set()
words.update("hi")
print(sorted(words))
words = set()
words.update(["hi"])
print(sorted(words))['h', 'i'] ['hi']
Storing the result
update() returns None. Use union() or | when you want a value back.
a = {1}
b = a.update({2})
print(b)
print(a | {3})None
{1, 2, 3}Questions people ask
How do I add a list to a set in Python?
s.update(my_list) adds each item. A list itself cannot be an element, because lists can change.
What is the difference between set.update() and dict.update()?
Both change the object in place. dict.update() sets keys and values; set.update() adds plain elements.