AquausDev AquausDev - 1 year ago 72
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'.


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

for num in number:
num = int(num)
if digits.index(num) % 2 == 0:
digits.insert(digits.pop(num-1), num * 3)
except IndexError:

for num in digits:
total += num

print(digits, total)

Answer Source

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



[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]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download