-1

I have several lists that I need to convert to sets. I wrote a function to do this, but when I try to dynamically create the sets variable it is not working. What would the correct syntax for this?

"s_" + listName = set(listName)

Error:

 "s_" + listName = set(listName)
    ^

SyntaxError: cannot assign to operator
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41
  • 1
    You can do it, but you shouldn't. If you're doing this in a function, the name it has inside the function doesn't matter to the caller anyway. Providing more context around how you're planning to use this function would make it easier to help you find a better solution. – Samwise Mar 29 '21 at 15:17
  • This is not possible the way you want it. You could use eval, but this is not a good idea. Try to dictionary with 's_'+Listname as the keys. – user_na Mar 29 '21 at 15:17
  • 1
    You need to use dictionaries: `dct = {'list_name1': set(list_name1), ...}` – Timur Shtatland Mar 29 '21 at 15:17
  • [Why you don't want to dynamically create variables](http://stupidpythonideas.blogspot.de/2013/05/why-you-dont-want-to-dynamically-create.html) – glglgl Mar 29 '21 at 15:18

1 Answers1

1

This is something which you can not do in (normal use of) python. You can use a dictionary instead.

lists = {
    "list1": [1, 2, 3],
    "list2": [4, 5, 6, 6]
}
sets = {}
for list_name, list_ in lists.items():
    sets["s_" + list_name] = set(list_)
print(sets)  # >>> {'s_list1': {1, 2, 3}, 's_list2': {4, 5, 6}}
miquelvir
  • 1,748
  • 1
  • 7
  • 21