im trying to reverse a list, here's my code, but for some reason, i keep getting an indexerror.
list1 = [1,2,3,4]
y = len(list1)
c = 1
for x in range(1,int(len(list1)/2)):
list1[c], list1[y] = list1[y], list1[c]
y -= 1
c = 1
so basically i want my output to be [4,3,2,1] why does it keep saying error?
CodePudding user response:
In Python, the first element is at an index of 0
, and the last is at len(lst) - 1
.
def reverse(xs):
i = 0
j = len(xs) - 1
while i < len(xs) // 2:
xs[i], xs[j] = xs[j], xs[i]
i = 1
j -= 1
Or more succinctly:
def reverse(xs):
for i in range(len(xs) // 2):
j = len(xs) - i - 1
xs[i], xs[j] = xs[j], xs[i]
CodePudding user response:
You can use slicing to reverse list here's how
listOrg = [1,2,3,4,5]
listReverse = listOrg[::-1]
print(listOrg)
print(listReverse)
CodePudding user response:
a = [1,2,3,4]
b = len(a) - 1
c = 0
for i in range(0,int(len(a))//2):
a[c] , a[b] = a[b] , a[c]
c = 1
b -= 1
print(a)
- You have took wrong start for indexing ie. c should be equal 0 as indexing starts from 0.
- The index in your 6th line "list1[y]" cannot be indexed as y is the length of list ie. 4 and the maximum index is only till 3.
CodePudding user response:
Consider go through the list from end to start:
new_reversed_list = []
for i in range(len(list1)-1, -1, -1)
new_reversed_list.append(i)
print(new_reversed_list)
CodePudding user response:
Your idea of having two indexes, start and end, is sane. However, there's no need to compute the number of iterations beforehand. Just keep iterating until start
becomes greater than end
:
start = 0
end = len(ls) - 1
while start < end:
ls[start], ls[end] = ls[end], ls[start]
start = 1
end -= 1