1

I am starting in python and I have this little problem, I have 2 lists and I want to switch the 2 middle values to create 2 more list and have 4 in total, like this:

p1=[3, 5, 2, 1, 4, 6]
p2=[5, 1, 3, 6, 2, 4]
s1=[3, 5, 3, 6, 4, 6]
s2=[5, 1, 2, 1, 2, 4]

I made this code:

p1=[3, 5, 2, 1, 4, 6]
p2=[5, 1, 3, 6, 2, 4]
s1=p1
s2=p2

for i in range(2,4):
    s1[i]=p2[i]
    s2[i]=p1[i]

print(s1)
print(s2)

The result is wrong, seems that 'p' and 's' are linked, how can i change it?: [3, 5, 3, 6, 4, 6] [5, 1, 3, 6, 2, 4]

jps
  • 20,041
  • 15
  • 75
  • 79

2 Answers2

1

When you are doing this:

s1=p1

You are saying: s1 is a pointer to p1, if you modify p1 you are also modifying s1

  • You can use the builtin list.copy() method (available since Python 3.3)
  • You can slice it: new_list = old_list[:]

there are multiple ways of coping values of list, take a look at:

List changes unexpectedly after assignment. How do I clone or copy it to prevent this?

Nja
  • 439
  • 6
  • 17
Zartch
  • 945
  • 10
  • 25
0

copy() is all you need:

p1=[3, 5, 2, 1, 4, 6]
p2=[5, 1, 3, 6, 2, 4]
s1=p1.copy()
s2=p2.copy()

for i in range(2,4):
    s1[i]=p2[i]
    s2[i]=p1[i]

print(s1)
print(s2)
Tugay
  • 2,057
  • 5
  • 17
  • 32