Reputation: 1
I am getting an error that says "IndexError: List index out of range" with the While Loop that I am using. Pls help.
from array import *
limit = 20
limitn = limit+1
p = 2
nums = range(p,limitn)
primes = []
while p < limitn+1:
for i in nums:
if i == p:
primes.append(i)
if i%p == 0:
nums.remove(i)
p = nums[0]
print primes
Upvotes: 0
Views: 27
Reputation: 4444
With nums.remove(i)
, nums
will be []
.
So, IndexError: List index out of range
is no problem
from array import *
limit = 20
limitn = limit+1
p = 2
nums = range(p,limitn)
primes = []
while p < limitn+1:
for i in nums:
if i == p:
primes.append(i)
if i%p == 0:
print(i)
nums.remove(i)
# Check nums array size
if len(nums) == 0:
break
p = nums[0]
print primes
Upvotes: 0
Reputation: 577
Your list goes out of index because at the last iteration the length of nums
is 0 i.e the list is empty and you are referencing the first element.
Because you are in a for loop nums.remove(index)
removes the index but does not update the list.
So nums
still refers to the previous nums
and it's length has been changed.
So instead of .remove()
use slice:
nums = nums[: nums.index(i)] + nums[nums.index(i) + 1 :]
slice operator creates a new nums
removing the element i
.
Your program for finding primes is not a good approach
for i in range(p, limitn):
for j in range(2, i):
if i % j == 0:
break
else:
primes.append(i)
The code above will give you primes in your range. If there is anything that can be improved please comment
Upvotes: 1