-1

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 reverse order, so [1, 2, 3] becomes [3, 2, 1].

i solved it by:

def reverse3(nums):
    return [nums[2]] + [nums[1]] + [nums[0]]

however, the answer is straight foward. My main question, how do i get nums reversed, when i don't know how many ints there are in nums?.

I've got this: nums[::-1] which does return nums reversed.but i'm looking for a different way. probably looping?

Iv'e tried this:

def reverse3(nums):
    return reversed(nums)

which returns: <list_reverseiterator object at 0x10151ff90> #location?

falsetru
  • 357,413
  • 63
  • 732
  • 636
Moh'd H
  • 247
  • 1
  • 4
  • 16
  • See also [python - list.reverse does not return list? - Stack Overflow](https://stackoverflow.com/questions/4280691/list-reverse-does-not-return-list) – user202729 Dec 20 '21 at 05:20

2 Answers2

0

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)
JWarren
  • 113
  • 5
0

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]
falsetru
  • 357,413
  • 63
  • 732
  • 636