Reputation: 429
i worte a code to reverse the elements of a list. here, i apply the algorithm that i run a loop form 0 to length of string, and interchange values as I go. i basically do a switch between two variables at a time using a third temp variable:
l = [1, 2, 3, 4, 5]
g = len(l) - 1
for i in range (0, len(l)):
m = l[i]
l[i] = l[g]
l[g] = m
g -= 1
print(l)
however, l prints as the original list. logically i am failing to see any flaws in the code. everything has been exchanged properly as far as i can see.
Upvotes: 0
Views: 56
Reputation: 416
#loop time should be len(1)/2
l = [1, 2, 3, 4, 5]
g = len(l) - 1
for i in range (0, len(l)/2):
m = l[i]
l[i] = l[g]
l[g] = m
g -= 1
print(l)
Upvotes: 0
Reputation: 309821
The problem with the logic is that you're looping over the entire list. Since you swap 2 elements at each turn of the loop, you only need to iterate over half the list to swap all the values.
In other words, when you iterate over the first half of the list indices, you reverse it. Then, when you iterate over the second half of the indices, you reverse it back.
As a side note, a really cool way to swap values in python is:
a, b = b, a
Or in your case:
l[i], l[g] = l[g], l[i]
Upvotes: 2