leob leob - 3 months ago 8
Python Question

Python: Generating list of numbers 1-10, but 1 ends up at the end of the list?

I have just started learning how to program using Python, and have been going through some exercises to help me improve. For one of the exercises, I have to program a Sieve of Eratosthenes, and as part of doing this, I wanted to generate a list of numbers 1 through n.

My code is as follows:

def primelist(n): #returns a list of all primes lower than or equal to n
grid=[]
k=1
while k in range (1, n+1):
grid.insert(-1, k)
k+=1
return grid


This is as far as I got, because when I tested what I had written so far with:

print(primelist(10))


my code output the list [2, 3, 4, 5, 6, 7, 8, 9, 10, 1] and I can't figure out why it is doing this. Any explanation would be much appreciated!

Answer

I don't know why it's backwards, but your code is not the way to add elements to a list. Also you don't use the variable n in your code (probably a typo), so I will just add the function to generate a list through 1 to n.

def primelist(n):
    grid=[]
    for k in range(1,n+1):
        grid.append(k)
    return grid

This code will return [1,2,3,4,5,6,7,8,9,10] as you requested.