Skip to content
Home » Python program that inserts and deletes elements in a list

Python program that inserts and deletes elements in a list

Python program that inserts and deletes elements in a list

val=list(eval(input("Enter list:")))
print("The list is:",val)
while True:
    print("Main Menu")
    print("1.Insert")
    print("2.Delete")
    print("3.Exit")
    ch=int(input("Enter your choice:"))
    if ch==1:
        item=int(input("Enter item:"))
        pos=int(input("Insert at which position? :"))
        index=pos-1
        val.insert(index,item)
        print("Success!List now is:",val)
    elif ch==2:
        print("Deletion Menu")
        print("1.Delete using value")
        print("2.Delete using index")
        print("3.Delete a sublist")
        dch=int(input("Enter choice:"))
        if dch==1:
            item=int(input("Enter item to be deleted:"))
            val.remove(item)
            print("List now is:",val)
        elif dch==2:
            index=int(input("Enter index of the item to be deleted:"))
            val.pop(index)
            print("List now is:",val)
        elif dch==3:
            l=int(input("Enter lower limit of list slice to be deleted:"))
            h=int(input("Enter upper limit of list slice to be deleted:"))
            del val[l:h]
            print("List now is:",val)
        else:
            print("Valid choices are 1,2,3 only!!!")
    elif ch==3:
        break
    else:
        print("Valid choices are 1/2/3 only.")

Output

Enter list:3,6,2,7,9,4

The list is: [3, 6, 2, 7, 9, 4]

Main Menu

1.Insert

2.Delete

3.Exit

Enter your choice:1

Enter item:7

Insert at which position? :5

Success!List now is: [3, 6, 2, 7, 7, 9, 4]

Main Menu

1.Insert

2.Delete

3.Exit

Enter your choice:2

Deletion Menu

1.Delete using value

2.Delete using index

3.Delete a sublist

Enter choice:1

Enter item to be deleted:6

List now is: [3, 2, 7, 7, 9, 4]

Main Menu

1.Insert

2.Delete

3.Exit

Enter your choice:2

Deletion Menu

1.Delete using value

2.Delete using index

3.Delete a sublist

Enter choice:2

Enter index of the item to be deleted:3

List now is: [3, 2, 7, 9, 4]

Main Menu

1.Insert

2.Delete

3.Exit

Enter your choice:2

Deletion Menu

1.Delete using value

2.Delete using index

3.Delete a sublist

Enter choice:3

Enter lower limit of list slice to be deleted:2

Enter upper limit of list slice to be deleted:4

List now is: [3, 2, 4]

Main Menu

1.Insert

2.Delete

3.Exit

Enter your choice:3