create a loop to reverse item in a list in python

To reverse items in a list using a loop in Python, you can follow these steps:

  1. Create an empty list to store the reversed items.
  2. Loop through the original list in reverse order.
  3. Append each item to the new list.
  4. Return the new list.

Here's the code:

main.py
original_list = [1, 2, 3, 4, 5]

reversed_list = []
for i in range(len(original_list)-1, -1, -1):
    reversed_list.append(original_list[i])

print(reversed_list)  # [5, 4, 3, 2, 1]
182 chars
8 lines

In this code, we first create a list original_list with some elements. Then we create an empty list reversed_list to store the reversed elements. Next, we loop through the original_list in reverse order using range() function, and append each element to reversed_list using the append() method. Finally, we print the reversed_list.

Note that we use range(len(original_list)-1, -1, -1) to loop through the list in reverse order. The range() function generates a sequence of numbers starting from len(original_list)-1 (which is the index of the last element in the list) down to 0, with a step size of -1 (i.e., counting down).

related categories

gistlibby LogSnag