Python: Append Values as Prefix or Suffix to a Set Elements

If you have a set and you want to append a prefix or a suffix to each element of that set then you can make use of the set comprehension in Python.


{expression for element in set}

cities = {"New York", "London", "Paris", "Tokyo", "Sydney", "Nairobi", "Dubai"}

welcome_cities = {"Welcome to " + city for city in cities}

for city_greeting in welcome_cities:

Welcome to Nairobi
Welcome to Paris
Welcome to Tokyo
Welcome to London
Welcome to Dubai
Welcome to Sydney
Welcome to New York

prices = {1.99, 5.49, 7.25, 12.50, 3.75}

prices_with_dollar = {"$" + str(price) for price in prices}

Append prefix to elements of a Python Set example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap