Reputation: 1071
I'm using the list
object by declaring
data = []
in my code, and without initializing it, I wrote
data += data2
Where data2
is another list
that contains lots of numbers.
An error happened at this line:
local variable 'data' referenced before assignment
How do I fix this?
Upvotes: 2
Views: 219
Reputation: 304393
Your problem is covered in the docs here
https://docs.python.org/3/reference/datamodel.html#object.iadd
For instance, if
x
is an instance of a class with an__iadd__()
method,x += y
is equivalent tox = x.__iadd__(y)
.
So you see data
is being rebound (to itself in this case), but it still counts as an assignment.
Since data += data2
appears inside a function scope where data
has not been declared to be global
, a local variable called data
is assumed.
def foo():
data.extend(data2) # ok -- global data variable here
def bar():
data = data.__iadd__(data2) # not ok -- local data variable here
def baz():
data += data2 # not ok -- equivalent to bar()
Upvotes: 0
Reputation: 4245
Getting 'referenced before assignment' after you initializing data can't happen if you are in the same scope.
The possibility is that you are creating a function (creating a new scope) so when you say data+=data2
it means
data = data + data2 # so what is data in the right hand side?
So if you want to refer the global variable use already available (global) data you have to explicitly say global data
or pass that as a parameter to the funciton.
Upvotes: 3
Reputation: 142909
If you use data += data2
in function you need global data
data = []
data2 = [1,2,3,4]
def add():
globla data
data += data2
add()
print data
or send data
as argument
data = []
data2 = [1,2,3,4]
def add(some_data):
some_data += data2
add(data)
print data
Upvotes: 0
Reputation: 2710
You may want to try using data.extend (data2)
instead of using the operator.
See this question for an extended discussion about adding two lists together: Python: take the content of a list and append it to another list
Upvotes: 1
Reputation: 1974
You have to initialize your array first. Here is a working example of how to fix this problem.
data = [0]
data2 = [1,2,3,4,5]
print data
data += data2
print data
Upvotes: 1