leob leob - 1 year ago 83
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
while k in range (1, n+1):
grid.insert(-1, k)
return grid

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


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 Source

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):
    for k in range(1,n+1):
    return grid

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download