how can I add one item over and over in a list in python
I am trying to make a list that records every pressed key and adds it to a list but when I am trying to append it it only changes the last item to the last pressed key
import keyboard
Keys = []
Keys.append(keyboard.read_key())
print(Keys)
Solution 1:
You will want to continuously call the second last lines in a loop, e.g.:
import keyboard
Keys = []
while True:
Keys.append(keyboard.read_key())
print(Keys)
However, this detects both key press and key release! For example, typing hey
outputs the following:
['h']
['h', 'h']
['h', 'h', 'e']
['h', 'h', 'e', 'e']
['h', 'h', 'e', 'e', 'y']
['h', 'h', 'e', 'e', 'y', 'y']
Instead of the read_key
approach, I would advise using keyboard.record()
instead, as that seems to be specifically aimed at recording keyboard inputs (documentation). This function also has support for e.g. until="esc"
, to specify when to stop recording.