Edwin Carlsson
Edwin Carlsson

Reputation: 15

Looping through arrays in Python3

Suppose I have a list of five different colours, colour = ['red', 'blue', ...] etc. I then want to create a loop for making an arbitrary amount of circles defined by the tkinter modules. That would mean something like

def Circles():
    y = 0
    x = 0
    while y <= 900 and x <= 900:
        x = x + 100
        y = y + 100
        w.create_oval(x, y, 0, 0, fill='red')

How would I include a loop for that fill='red' part, where I instead want fill=colour[N], where N would change in a loop? So the first circle would be red, next blue, next green etc? I also know that these ones overlap and I will try to make them not overlap, but that's not the question here.

Upvotes: 1

Views: 1128

Answers (4)

Frank-Rene Sch&#228;fer
Frank-Rene Sch&#228;fer

Reputation: 3352

I assume you may want to iterate over the plane of x an y. As for color, agreed, cycle is the right approach for the colors.

from itertools import cycle
def gen():
   color_cyclist = cycle('red', 'blue', 'green')
   for x in range(0,1000, 100):
       for y in range(0, 1000, 100):
           yield x, y, next(color_cyclist)

for x, y, color in gen():
    w.create(x, y, 0, 0, fill=color)

Upvotes: 0

DevLounge
DevLounge

Reputation: 8437

I would use itertools.cycle. Also as you increment both x and y by 100, up to 900, use range.

from itertools import cycle
colors = ['red', 'blue', 'yellow', 'green', 'orange']

def Circles():
    cycling_colors = cycle(colors)
    for i in range(0, 901, 100):
        w.create_oval(i, i, 0, 0, fill=next(cycling_colors))

Upvotes: 3

Keerthana Prabhakaran
Keerthana Prabhakaran

Reputation: 3787

def Circles():
    y = 0
    x = 0
    while y <= 900 and x <= 900:
        x = x + 100
        y = y + 100
        #iterate the colour list
        for colo in colour:
            w.create_oval(x, y, 0, 0, fill=colo) 

Hope it helps!

Upvotes: 0

Dmitry
Dmitry

Reputation: 2096

You can use this way, if you want to make nested loop:

colours = ['red', 'blue', 'green']

def Circles():
    y = 0
    x = 0
    while y <= 900 and x <= 900:
        x = x + 100
        y = y + 100
        for color in colours:
            w.create_oval(x, y, 0, 0, fill=colour)

Circles()

Upvotes: 1

Related Questions