Bread Bread - 1 month ago 16
Python Question

Set difference with iterable list

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'])




Answer

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.

Comments