returning the list reversed

后端 未结 2 935
一向
一向 2021-01-29 05:37

i have this question:

Write a function reverse3(nums) that takes a list of ints of length 3 called nums and returns a new list with the elements in reve

相关标签:
2条回答
  • 2021-01-29 06:18

    reversed returns an iterator. If you want to get a list object, use list:

    >>> def reverse3(nums):
    ...     return list(reversed(nums))
    ... 
    >>> reverse3([4,5,6])
    [6, 5, 4]
    
    0 讨论(0)
  • 2021-01-29 06:18

    List has a built in reverse function

    list.reverse()
    

    so you could use

    nums.reverse()
    

    However, if you want to write your own function you would need to do a reverse iteration to another list.

    Something like-

    def revList(nums)
       i = len(mums) -1
       while i >= 0:
          revNums[i] = nums.pop()
          i = i - 1
       return(revNums)
    
    0 讨论(0)
提交回复
热议问题