how to add an element in list using for loop and also without using append and also ask the position in which the number should be added

Viewed 22

i somehow used it in for loop to add an element using the user inputed position but i somehow get the last element of the list get deleted,

list1 = [int(item) for item in input("Enter the list(leave space for an element): ").split()]
n = len(list1)
print(f"Your list: {list1}")
add = int(input("Enter the number that should be inserted: "))
pos = int(input("Enter the position of that number should be inserted: "))

for i in range(n-1): 
    if(pos - 1 == i):
        for j in range(n-1, i-1, -1):
            list1[j]=list1[j - 1]
        list1[i]=add
        n += 1
           
print(list1)

can you guys please help me identify the problem

1 Answers
list1 = [int(item) for item in input("Enter the list (leave space between each element): ").split()]
n = len(list1)
print(f"Your list: {list1}")
add = int(input("Enter number to be inserted: "))
pos = int(input("Enter position to be inserted: "))
pos = pos -1

for i in range(n): 
    if(pos == i):
        list1.insert(pos,add)
print(list1)
Related