How can I make a list defined in one method available in another method when both methods are in the same class?

I have two methods within the same class, and I want to make a list in one method available in the other method, how do I do this?

Here is my code:

class Solution:
    primes=[]

    def primeNumber(self,n):
        numbers = set(range(n, 1, -1))
        self.primes = []
        while numbers:
            p = numbers.pop()
            self.primes.append(p)
            numbers.difference_update(set(range(p * 2, n + 1, p)))

    def goodNumbers(self,f):
        self.primes.append(f)
        return self.primes

x=Solution()
print(x.primeNumber(100)) ##populate the list
print(x.goodNumbers(123456789)) ##return the list as populated by previous call, and with the long number appended

For some reason, self.primes does not take into account the long number appended in goodNumbers()- any idea why this is?

Answer

As it has already been said, you can use an instance variable self.primes instead of your local variable primes. This is useful if you plan to reuse the values.

If instead you simply want to use the values once, and you want goodNumbers to call primeNumber, then simply add return primes at the end of primeNumber (outside the while loop of course)

EDIT

Since the question has been modified:

I just saw your edited question. That won’t work: if you’re using self.primes for passing data between methods then you need to first create it, probably at object initialization time, then to populate it with a call to primeNumber, and then you can read/modify it in goodNumbers.

For example:

class Solution:
    primes=[]

    def primeNumber(self,n):
        numbers = set(range(n, 1, -1))
        self.primes = []
        while numbers:
            p = numbers.pop()
            self.primes.append(p)
            numbers.difference_update(set(range(p * 2, n + 1, p)))

    def goodNumbers(self,n):
        self.primes.append(7598347534)
        return self.primes

x=Solution
x.primeNumber(100) ##populate the list
x.goodNumbers(123456789) ##return the list as populated by previous call, and with the long number appended