viligen

list_manipulator

Feb 6th, 2022
1,338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.21 KB | None | 0 0
  1. from collections import deque
  2.  
  3.  
  4. def list_manipulator(any_list, *args):
  5.     command = args[0]
  6.     position = args[1]
  7.     nums = [int(n) for n in args[2:]]
  8.     any_list = deque(any_list)
  9.     if command == 'add' and position == 'beginning':
  10.         any_list.extendleft(reversed(nums))
  11.     elif command == 'add' and position == 'end':
  12.         any_list.extend(nums)
  13.     elif command == 'remove' and position == 'beginning':
  14.         if nums:
  15.             for _ in range(*nums):
  16.                 any_list.popleft()
  17.         else:
  18.             any_list.popleft()
  19.     elif command == 'remove' and position == 'end':
  20.         if nums:
  21.             for _ in range(*nums):
  22.                 any_list.pop()
  23.         else:
  24.             any_list.pop()
  25.     return list(any_list)
  26.  
  27.  
  28. print(list_manipulator([1,2,3], "remove", "end"))
  29. print(list_manipulator([1,2,3], "remove", "beginning"))
  30. print(list_manipulator([1,2,3], "add", "beginning", 20))
  31. print(list_manipulator([1,2,3], "add", "end", 30))
  32. print(list_manipulator([1,2,3], "remove", "end", 2))
  33. print(list_manipulator([1,2,3], "remove", "beginning", 2))
  34. print(list_manipulator([1,2,3], "add", "beginning", 20, 30, 40))
  35. print(list_manipulator([1,2,3], "add", "end", 30, 40, 50))
  36.  
Advertisement
Add Comment
Please, Sign In to add comment