Here's a simple function foo
that takes an element and multiplies it by two. If it's a list, it will return the list of foo
-operated elements.
def foo(x):
if isinstance(x, list): ## Accepts list ONLY
return [foo(i) for i in x]
return x * 2
Output:
>>> foo(3)
6
>>> foo([1,2,3])
[2, 4, 6]
Edit:
Per Jon's comment, if you'd like a tuple
to be acceptable input, you could do the following:
def foo(x):
if isinstance(x, (list, tuple)): ## Accepts list OR tuple
return [foo(i) for i in x]
return x * 2
This will still return only a list
for either a list
or tuple
input, though. If you want the same type of output as input (i.e. tuple
output), then you can amend to the following:
def foo(x):
if isinstance(x, (list, tuple)): ## Accepts list OR tuple
result = [foo(i) for i in x]
return result if not isinstance(x, tuple) else tuple(result)
return x * 2
New output:
>>> foo(1)
2
>>> foo([1,2,3])
[2, 4, 6]
>>> foo((1,2,3))
(2, 4, 6)
Note also that this will handle odd nested structures:
>>> foo([[1,2,3],[4,5,6],(7,8,9)])
[[2, 4, 6], [8, 10, 12], (14, 16, 18)]