1

I'm wondering what is the Python way to perform the following - Given a set :

s = {'s1','s2','s3'}

I would like to perform something like :

s.addToAll('!')

to get

{'s1!','s2!','s3!'}

Thanks!

Ohad Dan
  • 1,929
  • 5
  • 17
  • 22
  • Tuples are immutable. See: http://stackoverflow.com/questions/626759/whats-the-difference-between-list-and-tuples-in-python – Alvin K. Apr 12 '13 at 05:49

2 Answers2

7

For an actual set:

>>> s = {'s1','s2','s3'}
>>> {x + '!' for x in s}
set(['s1!', 's2!', 's3!'])

That method is 2.7+, If you are using Python 2.6 you would have to do this instead:

>>> s = set(['s1','s2','s3'])
>>> set(x + '!' for x in s)
set(['s1!', 's2!', 's3!'])
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • nice but I feel he need for tuple your previous answer `[x + '!' for x in s]` – Grijesh Chauhan Apr 12 '13 at 05:38
  • @GrijeshChauhan That would result in a list, need to `tuple()` it still. – Stjepan Bakrac Apr 12 '13 at 05:39
  • @GrijeshChauhan I decided to answer the actual question which says sets, it is kind ambiguous so that's why I said "for an actual set" – jamylak Apr 12 '13 at 05:40
  • Yes jamylak it is ambiguous :) , @StjepanBakrac then `tuple([x + '!' for x in s])` I am also a new Python learner :) – Grijesh Chauhan Apr 12 '13 at 05:42
  • 2
    @GrijeshChauhan Or just `tuple(x + '!' for x in s)`, submit that if you want, it could be the answer – jamylak Apr 12 '13 at 05:43
  • @jamylak wait... `>>> (x + '!' for x in s)` doesn't answer tuple but `>>>[x + '!' for x in s]` answer list. theory is not clear to me Why? ..so I used typecast to tuple. – Grijesh Chauhan Apr 12 '13 at 05:47
  • 1
    @GrijeshChauhan The `tuple` constructor accepts an iterable to create a new tuple from it. That works with a list, `tuple([x + '!' for x in s])`, as you have shown. In Python if you remove the square brackets in a function call it uses a generator expression instead, which evaluates it's items lazily. – jamylak Apr 12 '13 at 05:49
0

You can try this:

>>> s = ['s1','s2','s3']
>>> list(i + '!' for i in s)
Priyesh Solanki
  • 707
  • 4
  • 6
  • Check the updated question, this is now wrong. Also you should always use `[i + '!' for i in s]` list comps instead of list constructor – jamylak Apr 12 '13 at 21:40