Python Forum

Full Version: Can I use a sublist as an argument in python?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a nested list:

city = [['house', 'street', 'park'], ['car', 'bike', 'train']]
Now I want to define a function what takes the first sublist of city as the input (argument) with the variable 'part', what takes the value 0 or 1 (depending on if I want to use the first or the second sublist:

def sublist(city[part]):
The editor returns the error:

def sublist(city[part]):
                ^
SyntaxError: invalid syntax 
Is it possible to use a sublist as an argument in python? If yes, how can I do it?
you need to do it like:
city = [['house', 'street', 'park'], ['car', 'bike', 'train']]

def sublist(element):
   print(element)

part = 0
sublist(city[part])
results:
Output:
['house', 'street', 'park']
You can do that, but you don't define a list index - [] - in a function definition. Instead just give it a name, e.g. city_sublist.
Then inside the function when you use the city_sublist you need to keep in mind what it is.

What do you want to pass as a argument to your function. The sublist directly, or just index (0 or 1) which will then select the sublist? from city?
Something like this
def sublist(arg_list, index=0):
    # do your stuff here
    # e.g.
    return arg_list[index]

city = [['house', 'street', 'park'], ['car', 'bike', 'train']]
print(sublist(arg_list=city, index=1))
print(sublist(arg_list=city)) # here using default value for index
Note that there may be other possible approaches to get the same result, depending on what your ultimate goal si