0

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 ?

3
  • should n be decared outside of the for loop? Commented Jul 28, 2022 at 15:17
  • 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). Commented Jul 28, 2022 at 15:17
  • 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. Commented Jul 28, 2022 at 15:18

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

Answer is you should use built in functions or operators mentioned in other answers

but if you want to keep using your own algorithms I made some modifications

list1 = [10, 20, 30, 40, 50]

n = 1
for items in list1:
    # length = len(list1)-1
    print("The reverse list is : ", list1[-n])
    n += 1

del list1

output of above code is:

The reverse list is :  50
The reverse list is :  40
The reverse list is :  30
The reverse list is :  20
The reverse list is :  10

Comments

0

You can use:

list1 = [10, 20, 30, 40, 50]

print(sorted(list1, reverse=True))

Output:

[50, 40, 30, 20, 10]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.