Search code examples
pythonsimplify

Simplify all variable and set them to false in Python


I'm not a Python master, but can anyone simplify this code because I thought there must be another way of writing this.

button1_clicked = False
button2_clicked = False
button3_clicked = False
button4_clicked = False
button5_clicked = False
button6_clicked = False
button7_clicked = False
button8_clicked = False
button9_clicked = False

It would be very helpful for anybody to answer me :) Thank you.


Solution

  • Since I only see arguably ugly (self confessed) unpythonic answers I feel compelled to offer another way:

    button_clicked = {i: False for i in range(1,10)}
    

    You can then use e.g. button_clicked[5] instead of button5_clicked.

    The benefit of this is you can now loop over all your buttons easily rather than having to address every single button individually...