So this is for a practice problem for one of my classes. I want to generate a list of 6 random numbers between 1 and 6. For example,startTheGame() should return [1,4,2,5,4,6]
I think I am close to getting it but Im just not sure how to code it so that all 6 numbers are appended to the list and then returned. Any help is appreciated.
import random
def startTheGame():
counter = 0
myList = []
while (counter) < 6:
randomNumber = random.randint(1,6)
myList.append(randomNumber)
counter = counter + 1
if (counter)>=6:
pass
else:
return myList
Use a list comprehension:
import random
def startTheGame():
mylist=[random.randint(1, 6) for _ in range(6)]
return mylist
List comprehensions are among the most powerful tools offered by Python. They are considered very pythonic and they make code very expressive.
Consider the following code:
counter = 0
myList = []
while (counter) < 6:
randomNumber = random.randint(1, 6)
myList.append(randomNumber)
counter = counter + 1
if (counter)>=6:
pass
else:
return
We will refactor this code in several steps to better illustrate what list comprehensions do. First thing that we are going to refactor is the while loop with an initialization and an abort-criterion. This can be done much more concise with a for in expression:
myList = []
for counter in range(6):
randomNumber = random.randint(1, 6)
myList.append(randomNumber)
And now the step to make this piece of code into a list comprehension: Move the for loop inside mylist. This eliminates the appending step and the assignment:
[random.randint(1, 6) for _ in range(6)]
The _
is a variable name just like any other, but it is convention in python to us e _
for variables that are not used. Think of it as a temp variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With