differences for creating set using set() or {}

  • A+

This subtle differences is confusing me. For example:

s = "()())()" print set(s)  >>>>> set([')', '('])   print {s}  >>>>> set(['()())()']) 



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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: