-3

I've a list. I make the copy of that list. Now I want to append a number into its copy not into the original list. How would I do that?

a = [1,2,3]
b = a
b.append(4)

print a,b # prints [1, 2, 3, 4] [1, 2, 3, 4]

I want [1, 2, 3] [1, 2, 3, 4]. How would I do that?

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267

2 Answers2

2

to copy the values, you should use

import copy
a = [1,2,3]
b = copy.copy(a)
b.append(4)

print a,b
Selva
  • 976
  • 1
  • 10
  • 23
  • 1
    @user1162512 If this answer helped you, please give it a +1 and accept it. –  Aug 05 '14 at 11:44
  • 2
    Easier to use `b = a[:]` to make a copy. No need to `import copy` (but no harm done this way either). –  Aug 05 '14 at 11:46
0

Its easier to use b = a[:] to copy a list.