Aman Shaikh
Aman Shaikh

Reputation: 3

whole list is not printed in reverse with using for loop

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 ?

Upvotes: 0

Views: 102

Answers (4)

X-_-FARZA_ D-_-X
X-_-FARZA_ D-_-X

Reputation: 544

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

Upvotes: 0

René
René

Reputation: 4827

You can use:

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

print(sorted(list1, reverse=True))

Output:

[50, 40, 30, 20, 10]

Upvotes: 0

Tanmay
Tanmay

Reputation: 46

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.

Upvotes: 1

Mitchnoff
Mitchnoff

Reputation: 515

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.

Upvotes: 1

Related Questions