Remove the last item from array Using Slicing Technique
Python3
# importing array from array module import array as a # initializes array with signed integers arr = a.array( 'i' , [ 1 , 2 , 3 , 4 , 5 ]) # printing original array print ( "The original array is : " , end = "") for i in range ( 0 , 5 ): print (arr[i], end = " " ) print () # using negative index to find last element print ( "The last element is : " , end = "") print (arr[ - 1 ]) # using slicing technique arr = arr[: - 1 ] print ( "The array after removing last element is : " , end = "") for i in range ( 0 , 4 ): print (arr[i], end = " " ) print () |
Output:
The original array is : 1 2 3 4 5
The last element is : 5
The array after removing last element is : 1 2 3 4
Explanation:
Here we simply find the last element using the negative indexing method and then update the original array with the updated one using the concept of slicing and removing the last element present in the array.
Python program to Remove the last item from array
Given an array, the task is to write a Python program to remove the last element in Python.
Example:
Input: [“geeks”, “for”, “geeks”]
Output: [“geeks”, “for”]
Input: [1, 2, 3, 4, 5]
Output: [1, 2, 3, 4]
Explanation: Here simply we have to remove the last element present in the
array and return the remaining array.
Note: Arrays are not supported in Python directly but they can be imported from the array module and used for the basic array operations.