Search code examples
pythonsetunion

How to write "set batch operation" in Python?


I'm a beginner in Python.

The codes that works is following:

a_set = set('a', 'b', 'c')
result_set = set()
for str1 in a_set:
    res = 'prefix-' + str1
    result_set.add(res)

The codes I want is similar to:

a_set = set('a', 'b', 'c')
result_set = set('prefix-' + c for c in a_set)

I think it may be more pythonic? But it doesn't work. What can I try next?


Solution

  • Use a set comprehension. The syntax is the exact same as a list comprehension except [ and ] are replaced with { and }, respectively.

    result_set = {'prefix-' + c for c in a_set}