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 ?
CodePudding user response:
Try this?
list1 = [10, 20, 30, 40, 50]
print(list(reversed(list1)))
What exactly is your end goal? This prints out the list in reversed order, but it seems like you are looking for something else.
CodePudding user response:
Why not try this?
list1 = [10, 20, 30, 40, 50]
for items in list1[::-1]:
print('The reverse list is :', items)
There are more ways to do this but since you wanted it in a loop format, this should do.