Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a value to an empty array in python

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading