-3
my_list=[1,2,3,4,5]
new_list=[]
for i in range(len(my_list)):
    new_list.insert(i,my_list[-1])
    my_list.pop(-1)

I used the above code to reverse a list but I was wondering why is the range(len(my_list)) necessary, more specifically, why doesn't it work if I simply put "for i in my_list:"?

jpp
  • 159,742
  • 34
  • 281
  • 339
Fariha Ahsan
  • 19
  • 1
  • 1
  • 1
  • 1
    `range(len(my_list))` return index list [0,1,2,3,4] instead of original list [1,2,3,4,5] – Viet Phan Feb 10 '18 at 02:33
  • Why do you think it *should* work with `for i in my_list`? – jpp Feb 10 '18 at 02:33
  • Because they're different code, they (often) have different behavior. What do you expect? – user202729 Feb 10 '18 at 02:35
  • Does this answer your question? [Traverse a list in reverse order in Python](https://stackoverflow.com/questions/529424/traverse-a-list-in-reverse-order-in-python) – Mig B Dec 26 '20 at 18:19

7 Answers7

1

List can be reversed using for loop as follows:

>>> def reverse_list(nums):
...     # Traverse [n-1, -1) , in the opposite direction.
...     for i in range(len(nums)-1, -1, -1):
...         yield nums[i]
...
>>>
>>> print list(reverse_list([1,2,3,4,5,6,7]))
[7, 6, 5, 4, 3, 2, 1]
>>>

Checkout this link on Python List Reversal for more details

kundan
  • 1,278
  • 14
  • 27
1
#use list slicing 
a = [123,122,56,754,56]
print(a[::-1])
vijayrealdeal
  • 19
  • 1
  • 1
  • 7
0

like this?

new_list=[]

for item in my_list:
    new_list.insert(0, item)
    # or:
    # new_list = [item] + new_list
f5r5e5d
  • 3,656
  • 3
  • 14
  • 18
0
def rev_lst(lst1, lst2):

    new_lst = [n for n in range(len(lst1)) if lst1[::-1]==lst2]
    return True

Could this be correct solution?

0

The simplest way would be:

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


for i in range(len(list1)-1,-1,-1):

    print(list1[i])
puchal
  • 1,883
  • 13
  • 25
0
lst = [1,2,3,400]
res = []

for i in lst:
    # Entering elements using backward index (pos, element)
    res.insert(-i, i)

print(res)
# Outputs [400, 3, 2, 1]
enzo
  • 9,861
  • 3
  • 15
  • 38
0
l = [10, 20, 30, 40, 50]
t = len(l) # ======>5 
for n in range(t-1,-1,-1):  # t-1 is 4 , -1 means 0 , decrement by-1 
    print(l[n]) 
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Pranab516
  • 1
  • 1
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful, of better quality and are more likely to attract upvotes. – rachwa Jul 19 '22 at 09:28