Instagram
youtube
Facebook
Twitter

Python program to insert elements at a given location in a list

A Python program to insert elements at a given location in a list

Short Description:
This Python program inserts a user-defined element at a specified position in a list. It first takes the element and the position as input, then uses the insert() method to add the element at the given index, and finally displays the updated list.

• A list is created.

• The user enters the element and the position to insert.

• The program checks if the position is valid.

• If valid, the element is inserted using the insert() method.

• The updated list is displayed.

• If the position is invalid, an error message is shown.

 

Program:

my_list = [11,22,33,44,55,66,77,88,99,90]

print("Original List:", my_list)

element = int(input("Enter the element to insert: "))

position = int(input("Enter the position (0-based index): "))

if 0 <= position <= len(my_list):

    my_list.insert(position, element)

    print("Updated List:", my_list)

else:

    print("Invalid position! Please enter a position between 0 and", len(my_list))