0

This function is intended to return lists containing the path and names of .tif files stored in a directory. However, when this function is ran the variables pthlist and nmlist are not visible in the Variable Explorer or printable.

def pathList (d): # input is directory path

    pthlist = [] # creating empty path list of .tif files in directory
    nmlist = [] # creating empty name list of .tif files in directory
    
    for item in os.scandir(d):
    
        if item.name.endswith(".tif"): 
             pthlist.append(os.path.join(d, item.name))
             nmlist.append(item.name) 
            
   return pthlist, nmlist
  • 4
    What do you mean it isn't "printable"? Can you show more code (perhaps where you run pathList and output the contents of the two lists? – Ryan Zhang Jun 05 '22 at 16:03
  • Keep in mind that you are not scoping correctly. If you intend `pthlist` and `nmlist` to be part of the global scope, you do not need to return them. Else you should put and initialize them into `pathList`. – Daniel F Jun 05 '22 at 16:04
  • "the variables pthlist and nmlist are not visible in the Variable Explorer or printable." Running a function does not cause variables to appear for the caller. Functions **do not** return variables; they return **values**. – Karl Knechtel Jun 05 '22 at 16:16
  • @DanielF [there is no "initialization" in Python](https://stackoverflow.com/questions/11007627/python-variable-declaration/11008311#11008311), and setting global variables requires an explicit `global` declaration. – Karl Knechtel Jun 05 '22 at 17:32

1 Answers1

1

After the edit you've done, you should be able to access the variables after they get assigned the result of the function call.

I've renamed the original variables by suffixing them with _temp to make it clear that they are not the same ones as the ones which you will continue using. They exist only temporarily during the execution of the function call or at least should be treated as such, as discardable, since only the returned result matters.

def pathList (d): # input is directory path
  pthlist_temp = [] # creating empty path list of .tif files in directory
  nmlist_temp = [] # creating empty name list of .tif files in directory
  for item in os.scandir(d):
    if item.name.endswith(".tif"): 
       pthlist_temp.append(os.path.join(d, item.name))
       nmlist_temp.append(item.name) 
  return pthlist_temp, nmlist_temp
  
pthlist, nmlist = pathList(d)
Daniel F
  • 13,684
  • 11
  • 87
  • 116