-1

I wrote a small script to reverse a list, but I always receive an empty one. I know other ways of reversing the list for (e.g) using the slicing notation, but I would like to know what is wrong in my method. Thanks in advance!

Code :

def reversing(t):
    temp =[]
    for i in t:
        if i<= len(t)-1:
            hew = t[-1-i]         
            temp.append(hew)
        return temp
reversing([10, 11, 12, 13, 14, 15])
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
cris bris
  • 1
  • 1

1 Answers1

2

There are a few errors.

First, I know what you wanted to do in the loop, but the variable i is not what you want. To use the variable i as an index for a list, you should use range() with len() here.

Secondly, an indentation error. Your code cannot loop due to the location of the return.

When you use for loop and it doesn work as you expected, easy way to find errors is using print(i) inside the loop. Then, you will easily find the gap between what you expected and what the code do.

I fixed your code, as follow:

def reversing(t):
    temp = []
    for i in range(len(t)):
        print(i) # This will help you understand how this loop works
        if i <= len(t)-1:
            hew = t[-1-i]
            temp.append(hew)

    return temp


result = reversing([10, 11, 12, 13, 14, 15])
print(result)
#[15, 14, 13, 12, 11, 10]
Park
  • 2,446
  • 1
  • 16
  • 25