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?
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]
def funky(*a): ... will allow you to call funky(1, 3) without those extra parensc.__getitem__(slice(*a)) works on both Python 2 and Python 3. But Daniels suggestion of c[slice(*a)] is better.retun c[slice(*a)]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]
0:1 a string if it's not inside " or '?