-1

What rule does this violate in python?

for i in range(12):
    'Array'+str(1)=[]

To me this should make 12 empty arrays named Array0 - Array12. However, I receive
SyntaxError: cannot assign to operator

What logic is this violating?

I'm thinking it might be reading this as
str(i)=[]

or that
'Array'+ str(i) is equal to []

Could someone confirm one or the other?

Michael
  • 749
  • 1
  • 8
  • 22
  • 1
    ``'Array'`` and ``'Array'+str(1)`` are strings, not a name. You cannot assign to strings. What makes you think this *should* work in the first place? What makes you think this is related to array creation? – MisterMiyagi Jan 15 '20 at 17:51
  • @MisterMiyagi I thought it was due to the way it was being created because the error states "cannot assign to operator" So I thought, okay, what operators am I using. Well there is a + and an =, so I figured it was one of those. – Michael Jan 15 '20 at 17:56
  • 2
    @Michal Basically, *all* of ``'Array'``, ``+`` and ``str(1)`` make invalid assignment targets. The error just can report only one. – MisterMiyagi Jan 15 '20 at 18:01

1 Answers1

3

'Array'+str(i) is a literal string, not a variable name, so you can't assign to it. It's like trying to assign 3 = 4.

Mark Snyder
  • 1,635
  • 3
  • 12
  • That makes sense now. Do you know if it is possible to dynamically generate and name a bunch of lists? – Michael Jan 15 '20 at 17:53
  • 3
    @Michael This thread will help you: https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables – Mark Snyder Jan 15 '20 at 17:55
  • So in Python are all variable names considered strings, but any sequence of characters surrounded by " or ' are considered string literals? – Michael Jan 15 '20 at 18:08
  • 1
    @Michael In general it's not wise to think of variable names as strings. You technically can access them as such using globals(), but there's almost never any reason to do so. Just think of them as their own thing: names. – Mark Snyder Jan 15 '20 at 18:20