How can I reverse a list in Python?

后端 未结 30 3167
既然无缘
既然无缘 2020-11-21 22:32

How can I do the following in Python?

array = [0, 10, 20, 40]
for (i = array.length() - 1; i >= 0; i--)

I need to have the elements of a

30条回答
  •  半阙折子戏
    2020-11-21 23:29

    With minimum amount of built-in functions, assuming it's interview settings

    array = [1, 2, 3, 4, 5, 6,7, 8]
    inverse = [] #create container for inverse array
    length = len(array)  #to iterate later, returns 8 
    counter = length - 1  #because the 8th element is on position 7 (as python starts from 0)
    
    for i in range(length): 
       inverse.append(array[counter])
       counter -= 1
    print(inverse)
    

提交回复
热议问题