-1

I shared a question last week and I don't think I was able to be very clear.

The code in python is this:

RESTRICTIONS = []
RESTRICTIONS.append(1)
RESTRICTIONS.append(2)
RESTRICTIONS.append(3)
RESTRICTIONS.append(4)
RESTRICTIONS.append(5)
for icont in range(3):
     'RESTRICTIONS' + str(icont) = RESTRICTIONS

That is, I want each new list to be renamed and receive, initially, the values ​​of the initial list. However, the following error is identified: SyntaxError: can't assign to operator.

martineau
  • 119,623
  • 25
  • 170
  • 301

3 Answers3

1

You can use exec to assign variables using another variable as the name:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 

But this is poor practice and should be generally avoided.
What you should use instead is a dict to store your values. Something like:

restrictions_log = {}
RESTRICTIONS = []
RESTRICTIONS.append(1)
RESTRICTIONS.append(2)
RESTRICTIONS.append(3)
RESTRICTIONS.append(4)
RESTRICTIONS.append(5)
for icont in range(3):
     restrictions_log[str(icont)] = RESTRICTIONS
Kasem Alsharaa
  • 892
  • 1
  • 6
  • 15
  • Be aware that every entry in `restrictions_log` refers to the same list now. – Matthias Feb 08 '20 at 18:29
  • Note, this will not work in local scopes. You'd have to handle the namespace yourself... in which case you might as well just directly use a `dict` – juanpa.arrivillaga Feb 08 '20 at 18:31
  • Thank you so much, it was almost what I needed. However, I needed to change the lists later, but I see that when I change, delete or insert values, the same is repeated for the other lists ... That's right? Is there any way to stop this? – Amanda Silva Feb 09 '20 at 00:36
0

When you use an assignment operator, you assign the value of what is on the right to the variable or element on the left. Example:

A = B + C Assigment operator = must always be the first operator from right to left. So in every programming language, this is impossible:

B + C = A

possible: A = 3*3+8 impossible: 3*3+8 = A

faris97
  • 402
  • 4
  • 24
0

Your question is unclear. Anyway. Looking at your previous question, is this what you are looking for ?

restrictions = []
restrictions.extend(range(1,6))
for i in range(3):
    print(f'restrictions.{i+1} = {restrictions[i]}')

If you like to do it with concatenation:

restrictions = []
restrictions.extend(range(1,6))
for i in range(3):
    print('restrictions.' + str(i+1) + ' = ' + str(restrictions[i]))

Hope it helps.

dEBA M
  • 457
  • 5
  • 19