how would I go about initiating a ‘randomDirection’ variable to hold a random value from the directions array, and set the lastDirection variable to an empty array in python?
Here is the code in JavaScript, how can I convert it into Python?
let lastDirection = [], randomDirection;
>Solution :
(Note that [] in Python creates a list, and not an array.)
Your question’s title seems to be asking a different question than your question’s body, so I’ll answer both.
To append an element elem to a list l in Python, you could do any of the following (I recommend looking into all three for the educational value):
l += [a]
l.append(a)
l.extend([a])
There are differences between those but each of those would result in l having a added as its last element.
To choose a random element from a list called directions and put it in lastDirection, you could use random.choice (remember to import random for this):
lastDirection = random.choice(directions)
If you want lastDirection to be an array and to just append directions to it as you go, then you could initialize it like so:
lastDirection = []
And then append elements to it using one of the methods noted above.