'Reverse list using for loop
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:"?
Solution 1:[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
Solution 2:[2]
#use list slicing
a = [123,122,56,754,56]
print(a[::-1])
Solution 3:[3]
like this?
new_list=[]
for item in my_list:
new_list.insert(0, item)
# or:
# new_list = [item] + new_list
Solution 4:[4]
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?
Solution 5:[5]
The simplest way would be:
list1 = [10, 20, 30, 40, 50]
for i in range(len(list1)-1,-1,-1):
print(list1[i])
Solution 6:[6]
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]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kundan |
| Solution 2 | vijayrealdeal |
| Solution 3 | |
| Solution 4 | |
| Solution 5 | puchal |
| Solution 6 | enzo |
