Hefaestion
Hefaestion

Reputation: 203

Function to return elements from a list in Python

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?

Upvotes: 0

Views: 187

Answers (3)

kezzos
kezzos

Reputation: 3221

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]

Upvotes: 4

Rahul K P
Rahul K P

Reputation: 16081

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]

Upvotes: 1

hawkjo
hawkjo

Reputation: 420

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.

Upvotes: 1

Related Questions