0

The program below will create a list of 100 numbers chosen randomly between 1-10. I need help to then sum the list, then average the list created.

I have no idea how to begin and since I'm watching videos online I have no person to turn to. I'm very fresh in this world so I may just be missing entire ideas. I would doubt that I don't actually know enough though because the videos I paid for are step by step know nothing to know something.

Edit: I was informed that what the program does is overwrite a variable, not make a list. So how do I sum my output like this example?

This is all I have to go on:

all I have to go on

Code:

import random

x=0
while x < 100:
    mylist = (random.randrange(1,10))
    print(mylist) 
    x = x+1
2
  • How to sum an output... use the sum function. Commented Dec 15, 2017 at 6:24
  • No it won't create a list, it will override the same variable you called mylist again and again with a random number Commented Dec 15, 2017 at 6:31

3 Answers 3

1

I think the shortest and pythonic way to do this is:

import random
x = [random.randrange(1,10) for i in range(100)] #list comprehension
summed = sum(x)                                  #Sum of all integers from x
avg = summed / len(x)                            #Average of the numbers from x

In this case this shouldn't have a big impact, but you should never use while and code manual counter when you know how many times you want to go; in other words, always use for when it's possible. It's more efficient and clearer to see what the code does.

Sign up to request clarification or add additional context in comments.

Comments

0
def sum(list):
    sm = 0
    for i in list:
        sm+=i
    return sm

Just run sum(list) to get sum of all elements

Or you can use

import random
x=0
mylist = []
sm = 0
while x < 100:
     mylist.append(random.randrange(1,10))
     sm += mylist[x]
     x += 1

Then sm will be sum of list

Comments

0

The code is not correct. It will not create a list but generate a number everytime. Use the below code to get your desired result.

import random
mylist = []
for x in range(100):
    mylist.append(random.randrange(1,10))
print(mylist)   
print(sum(mylist))

OR

import random
mylist = [random.randrange(1,10) for value in range(100)]
print(mylist)   
print(sum(mylist))

Output:

[3, 9, 3, 1, 3, 5, 8, 8, 3, 3, 1, 2, 5, 1, 2, 1, 4, 8, 9, 1, 2, 2, 4,
 6, 9, 7, 9, 5, 4, 5, 7, 7, 9, 2, 5, 8, 2, 4, 3, 8, 2, 1, 3, 4, 2, 2,
 2, 1, 6, 8, 3, 2, 1, 9, 6, 5, 8, 7, 7, 9, 9, 9, 8, 5, 7, 9, 4, 9, 8, 
 7, 5, 9, 2, 6, 8, 8, 3, 4, 8, 4, 7, 9, 9, 4, 2, 9, 9, 6, 3, 4, 9, 5, 
 3, 8, 4, 1, 1, 3, 2, 6]

 512

1 Comment

List comprehension is better.

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.