Python Forum
Can I use a sublist as an argument in python?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Can I use a sublist as an argument in python?
#1
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?
Reply
#2
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']
Reply
#3
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?
Reply
#4
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Sublist/ Subarray into string Python SantiagoPB 2 2,144 Apr-23-2021, 07:03 PM
Last Post: SantiagoPB
  SyntaxError: positional argument follows keyword argument syd_jat 3 5,861 Mar-03-2020, 08:34 AM
Last Post: buran
  List of objects with sublist medatib531 4 2,344 Mar-01-2020, 06:16 PM
Last Post: buran
  Insert into sublist if sublist is not having same no of records. parthi1705 10 4,521 May-28-2019, 12:01 PM
Last Post: perfringo
  Split List and Sublist from Pyodbc parthi1705 1 2,245 May-05-2019, 10:44 AM
Last Post: Larz60+
  merging sublist into single list in python abhishek8singhai 8 9,502 Mar-22-2019, 11:46 PM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020