Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I split an array out of function parameters

Given a fixed length list and a function

l = [1, 2, 3, 4, 5]
def printMiddle(first, middle, last):
    print middle
printMiddle(*l)

How do I force middle to print l[1:3] with the output below?

[2, 3, 4]
like image 231
Eric Fossum Avatar asked Apr 08 '26 06:04

Eric Fossum


2 Answers

You could do:

l = [1, 2, 3, 4, 5]

def printMiddle(*args):
    print(args[1:-1])

printMiddle(*l)

The asterisk * makes args a tuple of the positional arguments (parameters, as you have it) to the function. [1:-1] takes a slice of all but the first and last items in the tuple.

like image 141
jonrsharpe Avatar answered Apr 09 '26 18:04

jonrsharpe


Try this:

l = [1, 2, 3, 4, 5]
def printMiddle(lst,first, last):
    print lst[first:last]
printMiddle(l,1,4)

Although It would be much sensible to do like this:

l = [1, 2, 3, 4, 5]
print l[1:4]
like image 30
K DawG Avatar answered Apr 09 '26 19:04

K DawG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!