0
votes

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 ?

2
should n be decared outside of the for loop? - Thomas Bourne
list[-1] is always the last element of the list. you are shrinking the list and increasing n (for no reason, as it turns out). - chepner
Also, as the iterator advances towards the end of the list, the end of the list is moving towards the iterator at the same rate. They'll "meet" in the middle, meaning you'll only iterate over the front half of the list no matter how long the list is. - chepner

2 Answers

1
votes

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.

1
votes

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.