1

Hi I have problem understanding why is the output as such. I understand set difference between a string and a list (with one item). However, I dont really understand this as there are many items within the list l.

Could anyone explain? :)

It seems like it only take '1','4','9' and set difference it..

>>> l = ['3246', '82576', '2476', '19254', '83254', '92576', '19326', '1547', '325769', '3254698', '1', '254698', '354', '1932', '325', '9325', '1927', '32546', '4', '9']
>>> set('123456789')-set(l)
set(['3', '2', '5', '7', '6', '8'])
Bread
  • 135
  • 1
  • 13
  • 1
    `set('123456789')` = `{'1', '2', '3', '4', '5', '6', '7', '8', '9'}` and `'1'`, `'4'`, `'9'` appears in `l`. So if you remove `l` from the other set, you get `{'3', '2', '5', '7', '6', '8'}`. – Delgan Oct 22 '16 at 08:28

2 Answers2

2

The set command expects an iterable to convert to a set. Since you only give one string:

'123456789'

to the first set, it assumes this is it, and breaks this string to the set 1,2...,9 (strings). In l you only have '1','4', and '9' which correspond to these items, and so the difference removes them.

kabanus
  • 24,623
  • 6
  • 41
  • 74
0

Set expects an iterable to be passed to the constructor.

How does it know that an iterable is passed?

As this answer explains

The iter built-in checks for the iter method or in the case of strings the getitem method. To check if an object is "list like" and not "string like" then the key is the attributes getitem and iter:

 >>In [9]: hasattr([1,2,3,4], '__iter__')
 >>Out[9]: True
 >>In [11]: hasattr((1,2,3,4), '__iter__')
 >>Out[11]: True
 >>In [12]: hasattr(u"hello", '__iter__')
 >>Out[12]: False
 >>In [14]: hasattr(u"hello", '__getitem__')
 >>Out[14]: True

Thus, as a string is broken down to its individual components. And the further computation is performed.

Also, Set does not accept non-iterable values.

>>> set(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
Community
  • 1
  • 1
xssChauhan
  • 2,728
  • 2
  • 25
  • 36