Advertisement
Programmin-in-Python

Inserting element in a list at a given posiiton without builtin functions

Jan 7th, 2021
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.35 KB | None | 0 0
  1. def ListInsert(L1, pos, elem):
  2.     if pos > len(L1):
  3.         raise IndexError(f"Given Position '{pos}' is par the length of the List which is just {len(L1)}")
  4.     else:
  5.         FHalf = L1[:pos-1]
  6.         SHalf = L1[pos:]
  7.  
  8.         return FHalf + [elem] + SHalf
  9.  
  10. L1 = [1,2,3,4,5,6,7,8,9,0]
  11. L2 = ListInsert(L1, 9, 32)
  12. print("List After Changes : ", L2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement