Home > OS >  Storing value into a list
Storing value into a list

Time:10-07

factor= []
number= int(input("what is the number?"))
for i in range (1,number):
    remainder= number%i
    if remainder== 0:
       i= factor[i]
       print (factor[i])

it says list is out of range, I am trying to store i into the list

CodePudding user response:

You should see it in any tutorial - you have to use .append() to add element at the end of list.

Your list factor is empty and you can't get element using index factor[i] and you can put element in place factor[i] because it doesn't exist.

factor = []

#number = int(input("what is the number?"))
number = 12

for i in range(1, number 1):
    
    remainder = number % i
    
    if remainder == 0:
        factor.append(i)
        #print(factor)

# --- after loop ---

print(factor)

Result:

[1, 2, 3, 4, 6, 12]

And if you want to use index to put elements on list then first you should create list correct size (with some values - ie. 0)

factor = [0] * number

and later put data in selected places

factor[i] = i

but in your code this would give many 0 and it is not useful.

#number = int(input("what is the number?"))
number = 12

factor = [0] * (number 1)

for i in range(1, number 1):
    
    remainder = number % i
    
    if remainder == 0:
        factor[i] = i
        #print(factor)
       
# --- after loop ---

print(factor)

Result:

[0, 1, 2, 3, 4, 0, 6, 0, 0, 0, 0, 0, 12]

CodePudding user response:

number=[int(input("what is the number? "))]
print(type(number))
print(number)

will result in

what is the number? 5
<class 'list'>
[5]
  • Related