Differences for creating a set using set() or {}

From the Python documentation for the set() method:

Return a new set object, optionally with elements taken from iterable.

Since a string is an iterable, the set() method creates a set of all characters in the given string. However, since sets do not allow for duplicate values, the output is a set containing the two unique characters in the string: ')' and '('.

On the other hand, the shorthand syntax {s} creates a set out of all items between the curly brackets. Since you only inserted one item s (your string), the output was a set containing only that one item.

Leave a Comment