Search code examples
pythonlistkeypress

Python Keypressing - Printing list only when value changes


I'm trying to do the following thing:

Store keypress state in a list (False or True values) then if I press or unpress some key the list will be printed only if it's content changes and only once. (Keypress in this case)

I tried checking W A S D keys:

import keyboard

# List initializing
list = [False, False, False, False]
previous_list = [False, False, False, False]


while True:
     list[0] = keyboard.is_pressed("w")
     list[1] = keyboard.is_pressed("a")
     list[2] = keyboard.is_pressed("s")
     list[3] = keyboard.is_pressed("d")

     if list != previous_list:
         print(list)
         previous_list = list

Can you guys help me discovering why isn't it working ?

Thanks !!


Solution

  • First of all don't name variables with reserved keywords. as you know list is a reserved keyword. Now what is the problem in your case, the main problem is assigning lists, you are using = that is assigning also references and they are becoming the same arrays looking the same pointer so they will be equal after that. when you change list it will change previous_list too. The fix is simple you need to copy lists and let us also rename your variable.

    import keyboard
    
    # List initializing
    ls = [False, False, False, False]
    previous_list = [False, False, False, False]
    
    
    while True:
         ls[0] = keyboard.is_pressed("w")
         ls[1] = keyboard.is_pressed("a")
         ls[2] = keyboard.is_pressed("s")
         ls[3] = keyboard.is_pressed("d")
    
         if ls != previous_list:
             print(ls)
             previous_list = ls.copy()
             # previous_list = ls[:]
             # previous_list = list(ls)
    

    so by using copy() we are making a copy of the original list, you can also use previous_list = ls[:], or previous_list = list(ls)