Reputation: 1
I needed to write a custom reverse function, here is the code:
def reverse(x):
length = len(x)
out = x
for i in range(length):
out[length-i-1] = x[i]
return out
print(reverse([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]))
but for some reason this outputs [1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1]
, does anyone know why this is happening?
Upvotes: 0
Views: 65
Reputation: 207
Because you set out = x. And in python this is reference typed.
So in your loop, when you do out[0] = x[10], it sets out[0] to x[10], but it also sets x[0] to x[10] as x and out have the same reference.
If you want to create a reverse function from scratch, here is one of the best practices:
def reverse(my_list):
i = 0 # first item
j = len(my_list)-1 # last item
while i<j:
my_list[i], my_list[j] = my_list[j], my_list[i]
i += 1
j -= 1
return my_list
Upvotes: 1
Reputation: 1
def reverse(x):
length = len(x)
out = []
for i in range(1,length+1):
out.append(x[-i])
return out
Upvotes: -1
Reputation: 531868
out = x
doesn't make a copy: it just makes the name out
refer to the same list as the name x
.
While you can make a copy with something like out = x.copy()
or out = list(x)
, there's little reason to do so because you'll simply be overwriting every element of the resulting copy. Instead, just build a new list:
def reverse(x):
length = len(x)
out = []
for i in range(length):
out.append(x[length-i-1])
return out
There are other, simpler and/or faster ways to produce a reversed list (list comprehensions, slicing, using the reversed
type, etc) but I'll let you experiment with them on your own.
Upvotes: 2
Reputation: 2723
out = x
makes the variable out
point to the same list as x
. You probably want to do out = x.copy()
.
Upvotes: 0