Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python first argument of .insert cannot be 'str'

This was just a challenge I made up for myself and it’s really annoying. Would appreciate your help very much. I get the error saying on line 5 "’str’ object cannot be interpreted as an integer" for insert method but it checks and verifies at the top that the items in the list are int, which was unnecessery but I though just maybe I was wrong.

d = list(range(88))
print (type(d[4]))
for i in d:
    if i % 8 == 0:
        d.insert(d[i], "XOX")
    
print(d)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

To make you understand, see the below code:

d = list(range(88))
print("d is:\n", d)
for i in d:
    print("i is :", i)
    if i % 8 == 0:
        d.insert(d[i], "XOX")
    print("Now d is: ", d)

#output:

d is:
 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87]
i is : 0
Now d is:  ['XOX', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87]
i is : 0

When 'XOX' is inserted at 0th position, i value is again 0 since 0 is shifted towards right. Now, d[0] becomes 'XOX' that’s why you get error.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading