for loop and list populating - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: for loop and list populating (/thread-9492.html) |
for loop and list populating - mepyyeti - Apr-12-2018 Ok I built a very basic caesar wheel...(w/out modules/classes). There was more trial/error than I care to admit . But, I came across something I couldn't figure out. Here is the relevant snippet. base_wheel = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n', 'o','p','q','r','s','t','u','v','w','x','y','z'] new_wheel1 = [] new_wheel2 = [] spinner1 = random.randint(0,25) spinner2 = spinner1 for b in base_wheel: new_wheel1.append(base_wheel[spinner1]) spinner1 -= 1#no problem with decrementing for b in base_wheel: new_wheel2.append(base_wheel[spinner2]) #why does += 1 (below) go over range? I am looping elements of base_wheel #loop is finite so spinner2 must also terminate spinner2 +=1very puzzling to me... thx in advance... RE: for loop and list populating - buran - Apr-12-2018 What is unclear? You have some initial value and you add 26 to it. It will always be greater than 25 (max index in wheel). You don't have problem with decreasing, because python also supports negative indexes. I.e. base_wheel[-1] is z I.e any value between -25:25 is valid index RE: for loop and list populating - Larz60+ - Apr-12-2018 add a print statement on line 14: print('spinner1: {}, spinner2: {}'.format(spinner1, spinner2))and watch it. The error should become apparent RE: for loop and list populating - buran - Apr-12-2018 You may want to check modulo operator % |