0

I'm doing this repetitively:

item = func('item')
item1 = func('item1')
item2 = func('item2')

So I'm trying to write a code like this to do it faster:

list = [item, item1, item2]
for x in list:
  x = func(str(x))

However, it appears that as long as there are no quotes around the items they are only accepted as already existing variables. Is there a way to accomplish what I'm trying to accomplish?

ACan
  • 105
  • 1
  • 1
  • 7
  • Does this answer your question? [Dynamically assigning variable names?](https://stackoverflow.com/questions/26850361/dynamically-assigning-variable-names) – Btc Sources Jan 29 '21 at 22:02
  • You are trying to create variables dynamically which is not recommended. Read [this answer](https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables) for other approaches. – AnkurSaxena Jan 29 '21 at 22:02

1 Answers1

0

Are you looking for something like this?

list = ['item', 'item1', 'item2']
for x in list:
  x = func(x)

Also, note that in the above code you are replacing x with the result of the func which will be then thrown away in each iteration:

list = ['item', 'item1', 'item2']
for i in range(len(list)):
  list[i] = func(list[i])

you can also use map:

list = ['item', 'item1', 'item2']
list = List(map(func,list))

Edit: after reading the comments and the question again, I believe I misunderstood the question, but I will leave my answer here for the 'map' suggestion which I think is still relevant.

Nader
  • 152
  • 9