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!

1

2 Answers 2

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!'])
Sign up to request clarification or add additional context in comments.

7 Comments

nice but I feel he need for tuple your previous answer [x + '!' for x in s]
@GrijeshChauhan That would result in a list, need to tuple() it still.
@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"
@GrijeshChauhan Or just tuple(x + '!' for x in s), submit that if you want, it could be the answer
@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.
|
0

You can try this:

>>> s = ['s1','s2','s3']
>>> list(i + '!' for i in s)

1 Comment

Check the updated question, this is now wrong. Also you should always use [i + '!' for i in s] list comps instead of list constructor

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.