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?

1
  • list_a and list_b references the same list object. Commented Dec 27, 2014 at 7:04

2 Answers 2

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)]
Sign up to request clarification or add additional context in comments.

3 Comments

thank you for your help! BTW, is there more simple way if I want to decleare many lists in the same time?
@michaelhuang you can define variables at the same time like; a,b,c,d=1,2,3,4. So,do that on list variables.
@Pradhan tested and finally works elegantly! many thanks!! PS: a detailed way to declare many lists
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.