Fred James
Fred James

Reputation: 129

Change argument value of a function after function is called

I have a function that is called many times within a for-loop, something like this:

def drawPatch(win, x, y, colour):
    pass

cycling_colours = ['red', 'green', 'yellow', 'blue']

for i in range(25):
    for j in cycling_colours:
        drawPatch(win, x, y, j)

The colour is taken from a list and changes the colour of drawPatch each iteration. What I want to do is to grab the value of colour each iteration and store it in a list. I'm not sure how to go about doing this. I hope there's enough information here.

Upvotes: 0

Views: 100

Answers (2)

danuker
danuker

Reputation: 881

You could use an object. Pretty much the definition of an object is a bunch of functions, paired with state variables.

Objects are preferred to global variables because they're self-contained and you can pass them around.

class DrawTool:

    def __init__(self):
        self.colour_list = []   # Initialize an empty state

    def drawPatch(self, win, x, y, colour):
        self.colour_list.append(colour) # Modify the state

        #TODO: more code here
        pass


cycling_colours = ['red', 'green', 'yellow', 'blue']
my_tool = DrawTool()

for i in range(25):
    for j in cycling_colours:
        my_tool.drawPatch(win, x, y, j)

Upvotes: 1

user2555451
user2555451

Reputation:

j holds the value of each color. So, all you need to do is append j to a list:

cycling_colours = ['red', 'green', 'yellow', 'blue']
colors = []  # List to hold the values of j

for i in range(25):
    for j in cycling_colours:
        drawPatch(win, x, y, j)
        colors.append(j)

In the end, the colors list will hold all of the colors that you passed to drawPatch (each value of colour inside the function).

Upvotes: 2

Related Questions