3

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]
4
  • what u r passing to printMiddle function?? Commented Dec 24, 2013 at 17:06
  • What is the expected output? Please give examples of input-output. Commented Dec 24, 2013 at 17:07
  • Added finction call and output inline Commented Dec 24, 2013 at 17:09
  • Be more clear on your Question... Commented Dec 24, 2013 at 17:16

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.