0

I'm learing python(previously have a little c expericence) and am trying to solve a math problem but encountered something unexpected:

import math
list_a = list_b = [0 for k in range(10)]
print list_a[0] #test if list_a works]
for i in range(10):
    list_a[i] = math.sqrt(math.pi + i**2)
    print list_a[i]                                      #value
    list_b[i] = math.sqrt(list_a[i]**2 + math.pi**2)
    print list_a[i]                                      #why changed to another value?
    print '-----------------'

why after this line:

list_b[i] = math.sqrt(list_a[i]**2 + math.pi**2) 

the list_a[i] changed?

2 Answers2

1
list_a = list_b = [0 for k in range(10)]

Because list_a equal to list_b. So if list_b is changed, then list_a will change.

GLHF
  • 3,835
  • 10
  • 38
  • 83
1

list_a and list_b are labels for the same object. If you want them to be copies instead, do this:

list_a = [0 for k in range(10)]
list_b = list_a[:]

Another way would be to use list comprehensions and python's multiple assignments:

list_a, list_b, list_c = [[0 for k in range(10)] for i in range(3)]
Pradhan
  • 16,391
  • 3
  • 44
  • 59
  • thank you for your help! BTW, is there more simple way if I want to decleare many lists in the same time? – michael huang Dec 27 '14 at 07:10
  • @michaelhuang you can define variables at the same time like; _a,b,c,d=1,2,3,4_. So,do that on list variables. – GLHF Dec 27 '14 at 07:13
  • 1
    @Pradhan tested and finally works elegantly! many thanks!! PS: [a detailed way to declare many lists](http://stackoverflow.com/questions/2402646/python-initializing-multiple-lists-line) – michael huang Dec 27 '14 at 07:33