While printing the list in reverse it only prints till 50,40,30 but not the whole list , what it should print : 50,40,30,20,10 What is the input : 10,20,30,40,50 i want to solve this problem only using for loop (i know that we can use it like for i in range(size,-1,-1) but i dont want to do it that way , whats wrong in my code that it is just printing till 50,40,30
list1 = [10, 20, 30, 40, 50]
for items in list1:
length=len(list1)-1
n=1
print("The reverse list is : ",list1[-n])
del list1[-n]
n+=1`
1st iteration : length =5 n=1 The reverse list is : 50 10,20,30,40 n=1+1=2 2nd iteration : length = 4 n=2 The reverse list is :40 10,20,30 n=2+1=3 3rd iteration : length =3 n=3 The reverse list is : 30 10,20 n=3+1=4 This is the flow that my code is going through according to this it should return all the list in reverse but its not , where am i wrong ?
list[-1]
is always the last element of the list. you are shrinking the list and increasingn
(for no reason, as it turns out). - chepner