Remove and add item in a list using python

Python Python List (Article) Python List (Program)

331

Use the list methods, pop()insert() and append()

Given Input:

list1 = [54, 44, 27, 79, 91, 41]

Expected Output:

List After removing element at index 4  [34, 54, 67, 89, 43, 94]
List after Adding element at index 2  [34, 54, 11, 67, 89, 43, 94]
List after Adding element at last  [34, 54, 11, 67, 89, 43, 94, 11]

Program:

sample_list = [34, 54, 67, 89, 11, 43, 94]

print("Original list ", sample_list)
element = sample_list.pop(4)
print("List After removing element at index 4 ", sample_list)

sample_list.insert(2, element)
print("List after Adding element at index 2 ", sample_list)

sample_list.append(element)
print("List after Adding element at last ", sample_list)

Output:

Original list  [34, 54, 67, 89, 11, 43, 94]
List After removing element at index 4  [34, 54, 67, 89, 43, 94]
List after Adding element at index 2  [34, 54, 11, 67, 89, 43, 94]
List after Adding element at last  [34, 54, 11, 67, 89, 43, 94, 11]

Explanation:

  • pop(index): Removes and returns the item at the given index from the list.
  • insert(index, item): Add the item at the specified position(index) in the list
  • append(item): Add item at the end of the list.

This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.