0

I was making the difference between two sets to see what had changed when I noticed that whenever I had one element which was a repeated sequence it would be represented as only one char.

Example:

>>> set("aaaa") 
{'a'}

How can I represent it as {'aaaa'} so I can make the diff between two sets and get the right value? If it's not possible using sets, what is the easiest way to compare two data structures and get the diff in python3?

Example:

 >>> a = set(['red', 'blue', 'green'])
 >>> b = set(['red', 'green'])
 >>> a
 {'green', 'red', 'blue'}
 >>> b
 {'red', 'green'}
 >>> a - b
 {'blue'}
2
  • Your 2nd example works just like you want it. Could you describe more clearly what is wrong? Commented Jun 28, 2016 at 14:23
  • I was checking with set('aaa') and not set(['aaa']). Thanks Commented Jun 28, 2016 at 14:38

2 Answers 2

2

You don't call set on a single str unless you want to treat the str as a sequence of individual characters to be uniquified (that is, set('aaaa') is equivalent to set(['a', 'a', 'a', 'a']), because Python str are iterables of their own characters). If you want a set containing only "aaaa", you do either {'aaaa'} (set literal syntax) or set(['aaaa']) (set constructor wrapping a one-element sequence containing the str). The former is more efficient when you have a fixed number of items to put in a set, the latter works with existing iterables (e.g. set(mysequence)).

In Python 3.5+, you can use literal syntax more flexibly, creating sets from a combination of single values and iterables, e.g. {'aaaa', *mysequence} where mysequence is [1, 2, 3] would be equivalent to typing {'aaaa', 1, 2, 3}.

Sign up to request clarification or add additional context in comments.

Comments

1

If you're trying to set a variable to {'aaaa'} like in your example, simply change the set assignment from set("aaaa") to set(['aaaa']).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.