Enigmaderockz
Enigmaderockz

Reputation: 91

How to add variable to each item in a set in python

I have to add string --foo to each element in given set and been trying hard to do that but unable to do. Is it really possible to do that? Below is the set

a = {"apple", "banana", "cherry", "6363738", "1"}

output

a = {"apple--foo", "banana--foo", "cherry--foo", "6363738-foo", "1-foo"}

Upvotes: 0

Views: 138

Answers (4)

DirtyBit
DirtyBit

Reputation: 16772

For a change, using lambda:

>>> map(lambda x: x + '--foo', a)

OUTPUT:

>>> set(map(lambda x: x + '--foo', a)) # {'apple--foo', '6363738--foo', '1--foo', 'cherry--foo', 'banana--foo'}                                                                                                       

Upvotes: 0

siralexsir88
siralexsir88

Reputation: 418

Several ways to accomplish this, here is a simple for loop:

for i in range(len(a)):
    a[i] += "--foo"

Upvotes: 0

Leo Arad
Leo Arad

Reputation: 4472

You can try

a = {"apple", "banana", "cherry", "6363738", "1"}
{"{}--foo".format(i) for i in a}

or for Python 3.6 and above

{f"{i}--foo" for i in a}

Output

{"apple--foo", "banana--foo", "cherry--foo", "6363738-foo", "1-foo"}

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117866

You can use string concatenation in a set comprehension

>>> {i+'--foo' for i in a}
{'banana--foo', '6363738--foo', 'apple--foo', 'cherry--foo', '1--foo'}

Upvotes: 6

Related Questions