Home > database >  Passing Lists between Functions
Passing Lists between Functions

Time:11-13

Background - I have created 2 functions as part of a project to make API calls using values from an entities_list and views_list. The first function def user_inputs() asks for 2 user inputs as integer values (with v.basic error handling). The second function def url_constructor() iterates through the values in the 2x lists (using nested loops) and constructs URLs for my API call, before saving the URLs in the url_list, before a latter function will handle the API calls.

My issue - I am having issues accessing entities_list and views_list, specifically returning the lists from my def user_inputs() and having as arguments in the def url_constructor()

My code - you can see from this function, that I have attempted to return both lists respectively. Nothing breaks, and I can input my values into the list without issue -

def user_inputs():
    while True:
        try:
            entities_list = [int(x) for x in input("Entities for API Call:\n").split(', ')]
        except ValueError:
            print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
            return entities_list
            continue
        break
    while True:
        try:
            views_list = [int(x) for x in input("Views for API Call:\n").split(', ')]
        except ValueError:
            print("---ERROR: MUST BE COMMA SEPERATED VALUES---")
            return views_list
            continue
        break
    return entities_list, views_list
user_inputs()

However, we running the following code block for my def user_inputs(), I get a NameError: name 'entities_list' is not defined -

def url_constructor(entities_list, views_list):
    str = 'https://some_url/{}/view{}'
    for entity in entities_list:
        for view in views_list:
            url = str.format(entity, view)
            url_list.append(ur)
url_constructor(entities_list, views_list)

I am not looking for someone to do my work for me, however just guide me in the right direction. Your help is greatly appreciated!

CodePudding user response:

Look at the example below and try to apply to your code

def foo():
  list_a = [5]
  list_b = [12]
  return list_a,list_b

def bar(lst):
  print(lst)

a,b = foo()
bar(a)

CodePudding user response:

I think you need:

entities_list, views_list = user_inputs()

otherwise, the values returned from the user_inputs function get thrown away because they aren't assigned to anything.

Protip: you could also do:

url_constructor(*user_inputs())

https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists

  • Related