pythonpython-2.7

Print a list backwards


I have a code which i want to print this list backwards but it didn't work.

It prints [2 , 4 , 6 , 8 , 10, 10]

def printBackwards (list) :
  i = len(list) 
  while (i > 0):
  list.append(list[i-1])
   i = i +1
  print(list)
  return

myslist = [2 , 4 , 6 , 8 , 10]
printBackwards(myslist)

What i want is to print it [10 , 8 , 6 , 4 , 2] How can this be done ?

EDIT: I want use my code not [::-1] or reverse() or something from other post WHICH I have seen . so its not duplicate . I dont want just work from what ever code however I want to edit my code to work. Thanks.


Solution

  • def printBackwards(x) :
        i = len(x) 
        new_x = []
        while (i > 0):
            new_x.append(x[i-1])
            i -= 1
        print(new_x)
    
    myslist = [2 , 4 , 6 , 8 , 10]
    printBackwards(myslist)
    

    Use i-=1 to decrement the index and perhaps you might want to create a new variable to store the result.

    Alternatively, you can also append you result to the existing list and print out the second part after the loop.

    def printBackwards(x) :
        i = len(x)
        n = i
        while (i > 0):
            x.append(x[i-1])
            i -= 1
        print(x[n:])