0

For example, here's a function that takes 5 arguments and reverses the order

def reverseList(a,b,c,d,e): 
    normalList = [a,b,c,d,e] 
    reverseList = reversed(normalList) 
    printedList = [] 
    for eachit in reverseList:
        printedList.append(eachit)

    print "This is the list that was entered: %r" % (normalList)
    print "This is the same list, but in reverse: %r" % (printedList)

I'm new to this, so I can't figure out how to enter a "custom" list, e.g. not limit how many numbers can be entered in the function.

kmad1729
  • 1,484
  • 1
  • 16
  • 20
morr0564
  • 53
  • 7

1 Answers1

3

Just pass a list and return a list of the function reversed:

>>> def reverseList(li):
...    return list(reversed(li))
... 
>>> reverseList(['a', 'b', 'c'])
['c', 'b', 'a']

Works with a list of any length.


Or, as pointed out in comments:

>>> def reverseList(li):
...    return li[::-1]

If you are looking for support for a variable length of arguments rather than a list, use *args with the 'splat' * meaning your function is taking a tuple of unknown length (rather than named positional arguments):

>>> def reverseArgs(*args):
...    return args[::-1]
... 
>>> reverseArgs('a', 'b', 'c', 'd')
('d', 'c', 'b', 'a')
dawg
  • 98,345
  • 23
  • 131
  • 206
  • 2
    use li[::-1] . best way to [reverse](http://stackoverflow.com/questions/3705670/best-way-to-create-a-reversed-list-in-python) – kmad1729 Oct 19 '15 at 17:38