Home > Mobile >  Reversing a list without using append()
Reversing a list without using append()

Time:03-28

I don't know why I'm getting an error with the following code:

def reverse(lis):
    a = []
    for i in lis[::-1]:
        a =i
    return a
print(reverse([1,2,3]))

If I use the append() method, then it gives the correct answer. However, I'm looking for an approach that doesn't use append().

CodePudding user response:

You're really close. = performs the addition operation between an integer and a list, which isn't defined.

Instead, you should use = with a singleton list that contains the element:

def reverse(lis):
    a = []
    for i in lis[::-1]:
        a  = [i]
    return a
print(reverse([1,2,3])) # Prints [3, 2, 1]

CodePudding user response:

I think it is the simpliest way.

First we define the function with argument as array, so we can choose the array we want to reverse by simply typing it name on "()" Then we just print this array reversing it like reversing string. We are limitating the code to only 2 lines, also code should be clear and that's why i think it is the best solution You can also declare it as variable if you want to.

def reverse(array):
    print(array[::-1])

#for example
#reverse([1,5,9)
#output will be 9,5,1
  • Related