Positional arguments of variable size
Let's practice positional arguments of variable size. Your task is to define the function sort_types()
. It takes a variable number of positional arguments and checks if each argument is a number or a string. The checked item is inserted afterwards either in the nums
or strings
list. Eventually, the function returns a tuple containing these lists.
Use the Python's built-in isinstance()
function to check if an object is of a certain type (e.g. isinstance(1, int)
returns True
) or one of the types (e.g. isinstance(5.65, (int, str))
returns False
).
Types to use in this task are int
, float
, and str
.
This exercise is part of the course
Practicing Coding Interview Questions in Python
Exercise instructions
- Define the function with an arbitrary number of arguments.
- Check if
arg
is a number and add it tonums
if necessary. - Check if
arg
is a string and add it tostrings
if necessary.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Define the function with an arbitrary number of arguments
def sort_types(____):
nums, strings = [], []
for arg in args:
# Check if 'arg' is a number and add it to 'nums'
if ____:
nums.____
# Check if 'arg' is a string and add it to 'strings'
elif ____:
strings.____
return (nums, strings)
print(sort_types(1.57, 'car', 'hat', 4, 5, 'tree', 0.89))