0

I have a function:

def funky(a):
    c = [4,5,6]
    return c[a]

I would like to be able to call:

funky(0:1)

And

funky(0,1)

To get the same response [4,5]. How do I modify 'funky' to do this?

3 Answers 3

4

You can use the slice method directly on the list:

def funky(*a):
    c = [4,5,6]
    return c.__getitem__(*a)

print(funky(1, 3))
>>> [5, 6]
Sign up to request clarification or add additional context in comments.

4 Comments

Defining the function as def funky(*a): ... will allow you to call funky(1, 3) without those extra parens
What would be the Python 3 equivalent of this answer?
@Hefaestion: c.__getitem__(slice(*a)) works on both Python 2 and Python 3. But Daniels suggestion of c[slice(*a)] is better.
you can use also retun c[slice(*a)]
1

Enter slice(0, 1) as a parameter to your function as is. 0:1 won't work ever as it is not a passable parameter.

Comments

1
def funky(a,b):
    c = [4,5,6]
    return c[a:b+1]

And you can call funky(0,1), And you cant't call like funky(0:1). It's not a valid parameter.

You can call like funky('0:1') Because. If you need to take that kind of input take as string input and split with :

like this,

def funky(a):
        c = [4,5,6]
        x,y = map(int,a.split(':'))
        return c[x:y+1]

1 Comment

How is 0:1 a string if it's not inside " or '?

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.