Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a list of 6 random numbers between 1 and 6 in python

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
like image 570
wahlysadventures Avatar asked Oct 19 '15 22:10

wahlysadventures


1 Answers

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.

like image 77
Sebastian Wozny Avatar answered Sep 28 '22 15:09

Sebastian Wozny