0

I know there are better ways to do this, and I found some of them online too, but I want to know why this simple logic doesn't work.

p =[0,1,2,3,4]
q = p
U = 1

for i,elt in enumerate(p):
    print(p[i])
    if i + U > len(p)-1:       
        p[(i+U)-len(p)] = q[i]
    
   else:
        p[i+U] = q[i]

print(p)   

The output for this is:

0
0
0
0
0
[0, 0, 0, 0, 0]

2 Answers2

0

The problem with the code is that q and p are the same array, if you change one the other reflects those changes. Try changing the sencond line to this:

q = p.copy()

As on the line:

p[i+U] = q[i]

The every element is changed to the previous element, thus, all of them are now zero (the first element).

Drdilyor
  • 1,250
  • 1
  • 12
  • 30
  • Yes, I just saw how lists are defined in python. source : https://stackoverflow.com/questions/21704459/how-does-equating-lists-work-basic-concepts-of-mutable – Madhav Rawal Apr 07 '21 at 05:45
0

in the above code every time you are assigning the value present in the 0th index so in every loop from 0 to n-1 you keep on changing the original value with the 0th index value. so instead of doing that do :

p =[5,6,7,8,9,10]
q = p.copy()
U = 1

for i,elt in enumerate(p):
    print(p[i])
    if i + U > len(p)-1:       
        p[(i+U)-len(p)] = q[i]

    else:
        p[i+U] = q[i]

print(p)

OR YOU CAN USE :

p =[5,6,7,8,9,10]
n = len(p)
temp = [None] * (n * 2)
for i in range(n):
    temp[i] = temp[n+i] = p[i]

n2 = len(temp)
U = 1

arr = []
for i in range(n-U,n2-U):
    arr.append(temp[i])
print(arr)