-2
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
  • 147,904
  • 31
  • 244
  • 302
Fariha Ahsan
  • 21
  • 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

6 Answers6

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,208
  • 14
  • 27
1
#use list slicing 
a = [123,122,56,754,56]
print(a[::-1])
vijayrealdeal
  • 9
  • 1
  • 1
  • 6
0

like this?

new_list=[]

for item in my_list:
    new_list.insert(0, item)
    # or:
    # new_list = [item] + new_list
f5r5e5d
  • 3,456
  • 3
  • 13
  • 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,041
  • 10
  • 22
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,121
  • 2
  • 12
  • 36