AquausDev AquausDev - 13 days ago 5
Python Question

Odd and Unexpected "IndexError: pop index out of range"

I'm trying to append 7 numbers in a list, and times every other number by 3 (starting with 1) then place it back into the list. For some reason, the numbers '1234567' work fine and expected. However, when using the numbers '1324562' it returns and IndexError on the number 3'.

Code:

number = "1324562"
digits = []
old_list = []
total = 0

for num in number:
num = int(num)
digits.append(num)
old_list.append(num)
if digits.index(num) % 2 == 0:
try:
digits.insert(digits.pop(num-1), num * 3)
except IndexError:
print("*INCOHERENT SWEARING*")

for num in digits:
total += num

print(digits, total)

Answer

The trick is to separate the index from the contents - they are not related. Here is my solution to this:

number = "1324562"
digits = []

# enumerate returns the index number(i) and the item(n) as a tuple.
# A string is a sequence, so we can iterate through it
for i, n in enumerate(number):
    n = int(n)
    if i % 2 != 0:
        n *= 3
    digits.append(n)

print(digits)

Gives:

[1, 9, 2, 12, 5, 18, 2]

If you want the original string as a list (you have the variable old_list in your code) then you can create that with:

old_list = [int(n) for n in number]
Comments