0

I have a question about how to update a string within a function after calling it. I want it to save after I call the function. It's the equivalent of pressing "control+s" to save an excel file after you edit it. Here's example code:

def function():
    x=['string'];y=input();x.append(y)

What I want have have happen is: If I call this function 3 times over a month, I'd like to have it read: x=['string',input1,input2,input3]

It currently will only store x 2 values maximum. For example: x=['string',input1]

I understand that even if there is a way to update this string/function, the fact that I have x=['string'] at the start will always change x to x=['string'] when I call it...Is there a built-in way to do this and have it update the way I want it to?

10
  • Write the list to a file and then read from it? Commented Sep 22, 2015 at 15:45
  • @jonrsharpe I have a list with thousands of values. Every time call a value in this list, I want to add it to another list and then delete it from the current list. So there would be an "Unused" list and a "Used" list. Commented Sep 22, 2015 at 15:51
  • @jonrsharpe you're right, I should use pop. And yes the program would restart. I just want to be able to update the list after I call the function every time. Is this possible without a database or excel sheet? Commented Sep 22, 2015 at 15:57
  • @jonrsharpe What do you recommend? Commented Sep 22, 2015 at 15:58
  • @jonrsharpe I'm not sure where to do research without accidentally stumbling on the answer. Is there a specific place you know of that would have this answer? Commented Sep 22, 2015 at 16:11

1 Answer 1

1

Store the x in a class or a closure. You also might want to return x or you won't be able to retrieve its values:

def foo():
    x = []
    def bar():
        y = input()
        x.append(y)
        return x
    return bar

b = foo()

# usage
In [8]: b()
aaa
Out[8]: ['aaa']

In [9]: b()
bbb
Out[9]: ['aaa', 'bbb']

In [10]: b()
ccc
Out[10]: ['aaa', 'bbb', 'ccc']
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.