Home > Back-end >  How to combine elements in set and a string to a list in python?
How to combine elements in set and a string to a list in python?

Time:01-31

Have got a set() like

item = {'Apple','Lemon'}

and a string flow='Mango' need to combine both to form a list like below

result = ['Mango','Apple','Lemon']

tried the code result = [flow ,item] which doesn't work out. Help me through this. Thanks!

CodePudding user response:

You can unpack the set into a new list that includes flow:

result = [flow, *item]

CodePudding user response:

Add item to the set, conver the set to a list:

item.add(flow)
list(item)
# ['Apple', 'Mango', 'Lemon']

Or convert the set to a list and concatenate it with a list of flow:

[flow]   list(item)
# ['Mango', 'Apple', 'Lemon']

The second approach preserves the original set.

  • Related