In: Computer Science
programming in python
Design a program that initializes a list of 5 items to zero (use repetition operator). It then updates that list with a series of 5 random numbers. The program should find and display the following data:
-The lowest number in the list
- Average of the numbers stored in the list
import random
l1=[0]*5
for i in range(len(l1)):
l1[i]=random.randint(1,100)
print(l1)
print("The lowest number in the list is",min(l1))
print("Average of the numbers stored in the list
is",sum(l1)/len(l1))
Explanation -
1.we define a list l1 with one element 0 then using repetition operator we make 5 copies of this list and joins them together to make a single list of 5 items intialized to 0.
2.we then use for loop with number of iterations equal to len(l1)-1 using range function .We iterate through every element of list l1 using l1[i] where i is the index ranging from 0 till len(l1)-1 which is 4. And update every element with random value using randint function from random module .
randint function returns random value from specified range . in our case,it will return random value from 1 till 10 And update the list item with that value.
3.Finally we print the lowest number in the list using min function and average of the elements stored in list using sum of all elements in l1/size of l1.
if you dont wish to use min() function directly to find the lowest number , you can use below code instead -
minimum=l1[0]
for i in range(len(l1)):
if l1[i]<minimum:
minimum=l1[i]
print("The lowest number in the list is",minimum)
Here we initially define l1[0] i.e. first element as minimum and then we iterate through every element in l1 , if that element is less than minimum which is currently l1[0] then we make that element as minimum i.e. we replace l1[0] with that element.