codescracker
python

Python Program to Insert Element in a List



« Python Examples Python Tutorial »


This article is created to cover some programs in Python, that inserts an (or more) element(s) in a list at end or any particular index (or position). Both element and list must be entered by user at run-time. Here are the list of programs:

Insert an Element at the End of a List

This program inserts an element entered by user at the end of a list. The question is, write a Python program to insert an element in a list. Here is its answer:

# ----codescracker.com----

print("Enter 10 Elements of List: ")
nums = []
for i in range(10):
    nums.insert(i, input())
print("Enter an Element to Insert at End: ")
elem = input()
nums.append(elem)
print("\nThe New List is: ")
print(nums)

Here is its sample run:

python insert element in list

Now supply the input say 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 as ten numbers, then 11 as a number to insert in the list:

insert element in list python

In above program, the following statement:

nums.insert(i, input())

states that, entered value gets initialized at ith index of nums. For example, if user enters 10 and the current value of i is 2, then 10 gets initialized to nums[2]. Since initially the list nums is empty, then you can also replace the above statement with statement given below:

nums.append(input())

Note - The append() method appends an element (provided as its argument) at the end of list.

Note - An empty list can also be defined using nums = list()

Modified Version of Previous Program

This program allows user to define the size of list. The end used in this program, to skip inserting an automatic newline. The str() converts any type of value to a string type.

# ----codescracker.com----

print("Enter the Size: ", end="")
try:
    numsSize = int(input())
    print("Enter " +str(numsSize)+ " Elements: ", end="")
    nums = []
    for i in range(numsSize):
        nums.append(input())
    print("\nEnter an Element to Insert at End: ")
    elem = input()
    nums.append(elem)
    numsSize = numsSize+1
    print("\nThe New List is: ")
    for i in range(numsSize):
        print(end=nums[i] + " ")
    print()
except ValueError:
    print("\nInvalid Input!")

Here is its sample run with user input, 5 as size, 1, 2, 3, 4, 5 as five elements, 2 as element to insert at end of given list:

insert element in list at end python

Here is another sample run with user input, 11 as size, c, o, d, e, s, c, r, a, c, k, e as eleven elements, and then r as element to insert at end of list:

insert an element in list python

From above program, the following statement:

print(end=nums[i] + " ")

can also be written as:

print(nums[i], end=" ")

Note - The try-except is used to handle with invalid inputs. The first statement of try, that is numsSize = int(input()) gets executed, that wants to receive an integer input from user. But if user enters a non-integer value, then it raises an ValueError, therefore program flow goes to except ValueError's body and prints a message whatever the programmer specified.

Insert Multiple Elements at the End of a List

This program allows user to insert multiple (more than one) elements at the end of a list, at one execution of the program. Let's have a look at the program first:

# ----codescracker.com----

print("Enter Size: ", end="")
try:
    tot = int(input())
    print("Enter " +str(tot)+ " Elements: ", end="")
    arr = list()
    for i in range(tot):
        arr.append(input())
    print("\nThe List is:")
    for i in range(len(arr)):
        print(arr[i], end=" ")
    print("\n\nHow many element to insert ? ", end="")
    try:
        toti = int(input())
        print("Enter " +str(toti)+ " Elements: ", end="")
        for i in range(toti):
            arr.append(input())
        print("\nThe New List is:")
        for i in range(len(arr)):
            print(arr[i], end=" ")
        print()
    except ValueError:
        print("\nInvalid Input!")
except ValueError:
    print("\nInvalid Input!")

Here is its sample run with user inputs, 3 as list size and 1, 2, 3 as three elements, then 4 as size of elements to insert, then 5, 6, 7, 8 as four elements to insert:

python insert multiple elements in list at end

The dry run of above program with same user input as provided in sample run given above, goes like:

Insert Element at Specific Index (Position)

As you can see from very first program of this article, the insert() method is used to insert an element at a particular index number specified as its first argument. Therefore using insert() method, this program inserts an element at specified index by user at run-time:

# ----codescracker.com----

nums = []
print(end="Enter the Size: ")
numsSize = int(input())
print(end="Enter " +str(numsSize)+ " Elements: ")
for i in range(numsSize):
    nums.append(input())
print("\nEnter an Element to Insert: ")
elem = input()
print(end="At what index ? ")
pos = int(input())
nums.insert(pos, elem)
numsSize = numsSize+1
print("\nThe New List is: ")
for i in range(numsSize):
    print(end=nums[i] + " ")
print()

Here is its sample run with user input, 5 as size of list, 1, 3, 4, 5, 6 as five elements, 2 as element to insert, and 1 as index of element to store in the list:

insert element at specific position in list python

Note - To follow the position's value, then use, nums.insert((pos+1), elem) statement to insert element at given position. Because indexing starts with 0, but generally people referred the 0th index element as first position's element.

Insert Multiple Elements at Given Indexes in List

This is the last program of this article, that is a complete version of inserting multiple elements at given indexes in a list at one execution. This program also handles all type of invalid inputs using try-except:

# ----codescracker.com----

print("Enter Size: ", end="")
try:
    tot = int(input())
    print("Enter " +str(tot)+ " Elements: ", end="")
    arr = list()
    for i in range(tot):
        arr.append(input())

    print("\nThe List is:")
    for i in range(len(arr)):
        print(arr[i], end=" ")

    print("\n\nHow many element to insert ? ", end="")
    try:
        toti = int(input())
        arrdele = list()
        arrdeli = list()

        for i in range(toti):
            print("Enter Element and its Index Number: ", end="")
            arrdele.append(input())
            try:
                k = int(input())
                if k > (len(arr) + len(arrdele)):
                    print("\nInvalid Input!")
                    exit()
                arrdeli.append(k)
            except ValueError:
                print("\nInvalid Input!")
                exit()

        for i in range(toti):
            arr.insert(arrdeli[i], arrdele[i])
        print("\nThe New List is:")
        for i in range(len(arr)):
            print(arr[i], end=" ")
        print()

    except ValueError:
        print("\nInvalid Input!")
except ValueError:
    print("\nInvalid Input!")

Here is its sample run with user inputs, 3 as size, then 1, 2, 3 as its three elements, and 4 as number of elements to insert in entered list right now. Then 11 as first element and 0 as its index number. Again 22 as second element and 2 as its index number, then 33 as third element and 4 as its index number, and finally 44 as element and 6 as its index number:

insert multiple elements at any indexes in list python

Brief Description of Above Program

The program is created in a way that:

The dry run with exactly same user input as provided in previous sample run goes like. This is value evaluation dry run. The output statement does not involve in this dry run:


« Python Examples Python Tutorial »