Python's built-in list data structure is often used as an array because it can store a sequence of values of any data type. Lists can be created by using square brackets []
. Values are separated from one another by commas.
Because lists are mutable, their values can be changed after they are created. To access elements in a list, we can use indexing. A list's first element is indicated by an index of
#initalize the listnum_list = [1, 2, 3, 4, 5]#print the index of list elementprint(num_list[1])print(num_list[3])
With this understanding, let's discuss different ways through which we can remove the first element from a list in Python.
This method creates a new list that starts from the second element of the original list and assigns it back to the same variable. The original list is unchanged, and the first element is effectively removed.
#initalize the listnum_list = [1, 2, 3, 4, 5]print("The initial list:", num_list)#slice the list to remove the first elementnum_list = num_list[1:]print("List after removing the first element:", num_list)
The second column isn't added because the num_list[1:]
returns all elements within the num_list
starting from the index
pop()
This method eliminates the element at the specified index, in our case pop()
method and returns the list after removing the first element.
#initalize the listnum_list = [1, 2, 3, 4, 5]print("The initial list:",num_list)#remove the first element from the list using pop() method.num_list.pop(0)print("List after removing the first element:", num_list)
Note: The
pop()
method raises an IndexError if the are no elements in the list.
del
Using the del
keyword, we can remove the element at the specified index. The first element is removed from the modified version of the original list.
# initializing listnum_list = [1, 2, 3, 4, 5]# Printing original listprint("The initial list:", num_list)# using del list[0] to perform removaldel num_list[0]# Printing modified listprint("List after removing the first element:", num_list)
deque()
and popleft()
The popleft()
operation is used to remove the element from the front of the list after converting the list to a deque, which is a less usual method for carrying out this specific task.
from collections import deque# initializing listnum_list = [1, 2, 3, 4, 5]# Printing original listprint("The initial list:", num_list)# using deque() and popleft() to perform removalresult = deque(num_list)result.popleft()# Printing modified listprint("List after removing the first element:", result)
Note: The
deque()
method is used instead of a list in certain situations where we need to optimize performance, particularly for inserting and removing elements at the beginning and end of a list.
Inserting or removing elements from the beginning or end of a list can be slow because it requires shifting all subsequent elements by one position, resulting in a time complexity of deque()
has been optimized to provide constant time
resize()
This function in the Python numpy
library returns a new numpy
array with a specified size. The function takes two arguments, the input array and the new shape of the array.
The NumPy library is not part of the standard installation, so we must first install it to be able to use it with the given command:
pip install numpy
We must import numpy
and create the numpy
array in order to use this method. We rotate the array to the left by one index after determining the length of the array using the len()
method. To get our result, we pass the array to the resize function and set the shape parameter to len(array)-1
.
import numpy as np#creates the numpy arraynum_list = np.array([1,2,3,4,5])#print the initial listprint("The initial list:", num_list)#gets the length of the arraaynum_list_length = len (num_list)print("The length of the array is "+ str(num_list_length))# rotates the array to left by one indexx = num_list[0]for i in range(0,num_list_length-1):num_list[i]=num_list[i+1]num_list[i+1]=xprint("List after rotation:", num_list)# resizing the array using resize() functionnum_list.resize(num_list_length-1, refcheck=False)print("List after removing the element:", num_list)
Note: We cannot resize NumPy arrays that share data with another array in-place using the resize method by default. Referencing an array prevents resizing. We can disable reference checking using
refcheck=False
.
Let's compare all these methods together to see which one is the best:
The del
method: This is a simple and straightforward method for removing the first element of a list, but it can be inefficient for large lists since it requires shifting all the remaining elements.
The pop()
method: This method removes and returns the first element of a list and is efficient for small lists. However, it can also be inefficient for large lists since it requires shifting all the remaining elements.
The list slicing: This method creates a new list with all elements except the first one and is efficient for large lists since it does not require shifting any elements.
The deque()
method: This method is efficient for both small and large lists, as it is designed for efficient appends and pops from both ends of the list. However, it requires importing the collections module and creating a new object.
The appropriate method for removing the first element of a list depends on the specific use case. If efficiency is a concern, collections.deque
may be the best option. If memory usage is a concern, slicing may be the best option. If neither efficiency nor memory usage is a major concern, any of the methods may be appropriate.
In conclusion, the first element of a Python list can be removed using any of these techniques. Any selected method may be influenced by the particulars of our program's context and our preferences. Using the appropriate method to remove the first element of a list can help us write more efficient and concise code in our Python programs.
Free Resources