Generating a list of random integers in python 3 - python

I am getting a IndexError: list assignment index out of range error when trying to run this program. My index appears to be fine (0 through 8) and I don't think .append is needed since the equal sign assign the random value each pass. What am I missing?
import random
#The main function.
def main():
#Welcome message.
print("Welcome to the lottery number generator program!")
print()
#Explain what the program does.
print("Note: This program will randomly generate a 7 digit lottery number and display it to the screen. ")
print("________________________________________________________________________________________________")
print()
print()
#Call the generateNumbers function and store its returned list in variable lotteryNumbers.
lotteryNumbers = generateNumbers()
#Call the printLottery function and pass the lotteryNumbers list as argument.
printLottery(lotteryNumbers)
#The generateNumbers function generated 7 random digits between 0 and 9 stores them in a list and returns the list.
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = []
#Declare and set loop counter to 0.
index = 0
for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
index += 1
return lotteryNumbers
def printLottery(lotteryNumbers):
print("Here are the 7 lucky numbers: {}".format(lotteryNumbers))
#End main
main()

Lists are not like arrays in other languages!
lotteryNumbers is initialised as an empty list. There is nothing in it. Its length is zero. You need to add random.randrange(0, 10) to the empty list. This is done through .append()

for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
index += 1
This doesn't do what you're hoping it does. You can't assign a value to a position that doesn't currently exist in a list, and as that list is currently empty, that means you can't do this at all.
what you want is:
for index in range (0,8):
lotteryNumbers.append(random.randrange(0,10))
You don't need index += 1 because python handles this for you int the for loop.
by the way, lotteries are generally picked without replacement, so don't you actually want to sample?
https://docs.python.org/2/library/random.html#random.sample
eg:
lotteryNumbers = random.sample(xrange(10), 7)
although it is also normal for lotteries to have far more than 10 options!

By initializing an list with
lotteryNumbers = []
it has exactly 0 elements. But with
lotteryNumbers[index] = random.randrange(0,10)
You try to access the 1st, the 2nd, .. , nth element of the list. Your code does not insert elements to the list. To avoid this there are serveral approaches.
Create a dict instead of a list. A dict actually creates nonexistent elements: lotteryNumbers = {}
Preinitialize the list with 8 elements:
lotteryNumbers = [0,0,0,0,0,0,0,0]
or lotteryNumbers = list(range(8))
But the most preferable variant should be to use append:
lotteryNumbers.append(random.randrange(0,10))

You should append the new values:
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = []
#Declare and set loop counter to 0.
index = 0
for _ in range (0,8):
lotteryNumbers.append(random.randrange(0,10))
return lotteryNumbers
or build the list up to the size you want:
def generateNumbers():
#A list variable to hold empty list.
lotteryNumbers = [0]*8
#Declare and set loop counter to 0.
index = 0
for index in range (0,8):
lotteryNumbers[index] = random.randrange(0,10)
return lotteryNumbers
Also notice you dont neet to increment the index, you are already iterating through the range.

You are trying to access non-existing elements of the list.
To build your list, you can either keep appending to it with list.append():
lotteryNumbers = []
for _ in range(8):
lotteryNumbers.append(random.randrange(0,10))
or, as it's common in Python, use a list comprehension:
lotteryNumbers = [random.randrange(0,10) for _ in range(8)]
which is usually more efficient and succinct.

I thinks you try add element to array like
lotteryNumbers = [0,0,0,0,0,0,0]

This works. Make an array with the numbers you want and select randomly one item. Then, delete that item and decrease the length with one (using pop). In this example the numbers 1 till 7
lotteryNumbers = []
rij = []
for i in range(aantal):
rij.append(i)
for j in range(7):
r = random.randrange(0,7-j)
k = rij.pop(r)
lotteryNumbers.append(k+1)
print(lotteryNumbers)

Related

Sum not performing addition on the list specified in python

So i've got the list, i've changed it from strings to integers and now i need to add them all up for a total. The only thing is, my code is not doing the calculation, even when the function is called. Here's my code;
# create an empty list for your products.
products = []
# Asking for the number of elements to be inputted.
n = int(input("Enter number of products you're buying : "))
# Some UI for the customer.
print("What are these products?")
# iterating until the range that has been chosen.
for i in range(0, n):
ele = input()
products.append(" - " + ele) # adding the element
def totalPrice():
price = [int(cost[i])]
print(sum(price))
# Some UI for the customer.
print("How much do those items cost?")
# create an empty list for your prices.
cost = []
# iterating until the range of the products array.
for i in range(products.__len__()):
ele = str(input())
cost.append(ele) # adding the element
# concatenating the lists, putting them in descending order and displaying them.
newList = [i + j for i, j in zip(cost, products)]
newList.sort(reverse=True)
print("Your products are : " + str(newList))
totalPrice()
The function should change the 'cost' list of strings to integers in a new list and add them all together, if i try to target the index of the 'price' list, it gives mean an iteration error.
Do i need to specify addition? Am i using the wrong function?
In the function,
price = [int(cost[i])]
This puts a single element into the list price, using the global value of i that was left over after that for i in range(products.__len__()): loop ran at the top level. (Incidentally, don't call .__len__() yourself - the built-in len is designed to do it for you - and don't loop that way anyway.)
if i try to target the index of the 'price' list, it gives mean an iteration error.
I have no idea what this is supposed to mean.
If you want to build a list of values corresponding to the original list, then you need to actually do that - either by iterating with a for loop, or using a comprehension:
price = [int(c) for c in cost]

Trying to insert value in list from user in for loop raises IndexError

How many values he/she want to add and then he insert values using loop.
I use this loop for sorting:
value = int(input("how many number u want to add"))
arr = [value]
for n in range(0, value):
arr[value] = input("Enter value")
for n in range(0, value):
print(arr[value])
It shows the error:
arr[value] = input("Enter value")
IndexError: list assignment index out of range
If you think that doing arr = [value] will create an array of length value, then you're wrong, it just creates a list that has one element, value, if you want to create a list that has value length, you can use list multiplication:
value = int(input("how many number u want to add"))
arr = [0] * value
for n in range(value):
arr[n] = input("Enter value")
for n in arr: # iterate over the elements directly, rather than indexing
print(n)
And another way is to use list.append to dynamically add elements to a list:
value = int(input("how many number u want to add"))
arr = []
for n in range(value):
arr.append(input("Enter value"))
for n in arr:
print(n)
I don't think arr = [value] is what you meant to write. Did you mean to make an empty array/list with that many values? If so, you can do that by arr = [0]*value which will fill your array with zeros and will be 'value' elements long. Creating the list to the exact size you want on creation is a good idea to help speed up your code a little bit (relative to creating an empty list and appending every value). In this tiny example, it will not be noticed, but larger scale projects can benefit from this kind of thing.
In your for loop, the n variable is your index into the array, so change arr[value] = input("Enter value") to arr[n] = input("Enter value"). Side note: Any values added this way will be strings and not integers.
Same as (2) for your second for loop, print(arr[value]) should be print(arr[n]).

How to use append to store values within a loop in Python

I'm defining a function (results) that contains a for loop whose result is a random number (a). So, if the loop runs 10 times, for example, it will generate 10 different numbers. I would like to store those numbers in a list within the loop that I could then print to see what numbers were generated.
I thought of using append, though I don't know how to do this. This is my code so far, though the print statement doesn't work (I get an error saying I didn't use append correctly).
import maths
def results():
items = []
for _ in range(1,10):
a = maths.numbers()
items.append(a)
print(items)
You could do something like this:
import maths
list_with_numbers=[]
def results():
for _ in range(1,10):
a = maths.numbers()
list_with_numbers.append(a)
print(list_with_numbers)
It is obvious, but donĀ“t forget to all the function itself.
.append needs to be called on the list, not on a. list also needs to be initialized outside of the loop in order to be able to append to it. Here's a fixed version of your method:
from random import random
def results():
# First, initialize the list so that we have a place to store the random values
items = []
for _ in range(1,10):
# Generate the next value
a = random()
# Add the new item to the end of the list
items.append(a)
# Return the list
return items
Here is some more documentation on the append() method that further explains how it works.
It's also worth noting that range generates values from the start value up to (but not including) the stop parameter. So if your intent was to generate 10 values, you should do range(0, 10) since range(1, 10) will only give you 9 values.
If you wanted to take this a step further, you could use a list comprehension to avoid needing to use append altogether, and provide a parameter to indicate how many random numbers you want:
def results(num=10):
return [random() for _ in range(0, num)]
# produces a list of 10 random numbers (by default)
foo = results()
# produces a list of 20 random numbers
bar = results(20)
append is a method you have to use on the list, so basically you would do like this: randomList.append(a) and don't forget to initialize your liste beforehand at the beginning of your function: randomList = []
You have a few minor mistakes
there is no maths module
a is the number, not the list. You should append on a list
you call print after the loop ends, not on every iteration
from random import random
def results():
numbers = []
for _ in range(1,10):
a = random()
print(a)
numbers.append(a)
return numbers

why is it giving index error out of range although i am almost sure I am in range?

i was trying to fill a list with inputs, but it gave me index out of range
although the index is starting from zero, as far as i know we don't have to specify the length of a list in python.
inputs = input("Enter the number of inputs: ")
lists = []
k = 0
while k<inputs:
lists[k]= input()
k+=1
Because you are creating an empty list with lists = [] and then accessing an element of this empty list. This is the cause of the IndexError.
Appending with lists.append() helps you avoid index errors like this one. You generally want to use indexing when accessing elements and not when populating the list.
You can initialize your list before using indexes of it:
lists = [0] * int(inputs)
And then you can use your code
Use list.append() to add an element to the end of the list:
while k<inputs:
lists.append(input())
k+=1
or with a list comprehension:
lists = [input() for _ in range(inputs)]
Another possibility: Initialize lists as an empty list and then append the input with the += operand.
lists = []
k = 0
while k < inputs:
lists += [input()]
k+=1

IndexError: list assignment index out of range for arrays

I am new to python. I think n begins at 0 and it will increase up till the last element on stack1.
arraylength = 3*stack1length
array = [0]*arraylength
for n in stack1:
array[3*n] = stack1[n]
my array length is 3 times the length of stack1
for n in stack1:
Goes through the items in stack1.
You seem to be wanting to go through the indexes:
for n in range(len(stack1)):
array[3*n] = stack1[n]
Note that this is better written with the convenience function, enumerate,
for n, stack1_n in enumerate(stack1):
array[3*n] = stack1_n
Additionally, you can use some evil hackz:
array[::3] = stack1
array[::3] is every third item in array (start:stop:step), and therefore you're setting every third item to the corresponding item in stack1.

Categories