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]
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With