0

I am making an program that simulates the roll of a dice 100 times. Now I want to sort the output of the random numbers that are given by the program. How do I have to do that?

import random

def roll() :
    print('The computer will now simulate the roll of a dice 100 times')
    list1 = print([random.randint(1,6) for _ in range(100)])

roll()

3 Answers 3

4

You do not have a list. The print() function returns None, not whatever it just printed to your terminal or IDE.

Store the random values, then print:

list1 = [random.randint(1,6) for _ in range(100)]
print(list1)

Now you can just sort the list:

list1 = [random.randint(1,6) for _ in range(100)]
list1.sort()
print(list1)
Sign up to request clarification or add additional context in comments.

3 Comments

When i follow your instructions and run the program, it prints the random numbers, but then it prints 'None' and it doesn't show a sorted list. How do i have to fix this?
Use return list1 to return the list from the roll() function.
And don't print*` the list1.sort() call, it returns None as it sorts the list *in place.
2

The above problem can also be solved using for loop as follows -

>>> import random

>>> mylist = []

>>> for i in range(100):
        mylist.append(random.randint(1,6))


>>> print(mylist)

To sort the list, issue the following commands -

>>> sortedlist = []
>>> sortedlist = sorted(mylist)
>>> print(sortedlist)

1 Comment

Better than the accepted answer :)
0

If you don't need the original list:

list1.sort()

If you need the original list:

list2 = sorted(list1)

See python.org: http://wiki.python.org/moin/HowTo/Sorting/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.