Home > Software engineering >  Edit function code to append results into empty list
Edit function code to append results into empty list

Time:05-03

I have a function below, where I'd like to append the results of each like into an empty list so that I can call that list outside of the function.

How can I adjust it? Currently there's no error but it simply prints "[]" when print(cd) when I print outside of the function. I'd like to be able to put the new data in a list, then recall it outside of the function.

 cd = [] # started empty list
def split_lines(lines, delimiter, remove = '[0-9] $'):
  for line in lines:
    tokens = line.split(delimiter)
    tokens = [re.sub(remove, "", token) for token in tokens]
    cleaned_list = list(filter(lambda e:e.strip(), tokens))
    cd.append(cleaned_list) # tried appending here
    print(cleaned_list)

CodePudding user response:

This might be your problem:

You have to call split_lines and then print cd.

cd = [] # started empty list
def split_lines(lines, delimiter, remove = '[0-9] $'):
  for line in lines:
    tokens = line.split(delimiter)
    tokens = [re.sub(remove, "", token) for token in tokens]
    cleaned_list = list(filter(lambda e:e.strip(), tokens))
    cd.append(cleaned_list)
split_lines("call me first", " ")
print(cd)
btw - cd is not a good name to use its a terminal command.

CodePudding user response:

Some issues I noticed

1 - print(cleaned_list) Do you want to print the cleaned_list or cd

2 - If .append() doesn't work for some reason, maybe do

cd = [] # started empty list
def split_lines(lines, delimiter, remove = '[0-9] $'):
  for line in lines:
    tokens = line.split(delimiter)
    tokens = [re.sub(remove, "", token) for token in tokens]
    cleaned_list = list(filter(lambda e:e.strip(), tokens))
    cd = cd   cleaned_list
    print(cleaned_list)

I don't get why append wouldn't work but just in case.

  • Related