Saturday, November 16, 2024
Google search engine
HomeLanguagesPython | Perform append at beginning of list

Python | Perform append at beginning of list

The usual append operation of a Python list adds the new element at the end of the list. But in certain situations, we need to append each element to the front of the list. If we perform brute force techniques, we need to perform unnecessary shifts of elements and hence, having shorthand for it is useful.

Example

Input: [1, 3, 5, 7, 9]
Output: [100, 1, 3, 5, 7, 9]
Explanation: In the above list we have added the '100' at index=0

Add Element to Front of List in Python

Let us see a few different methods by which we can append a value at the beginning of a Python list.

  • Using Insert() Method
  • Using [ ] and + Operator
  • Using List Slicing
  • Using collections.deque.appendleft()
  • using extend() method
  • using list() and itertools.chain() Functions
  • Using numpy.concatenate() Function
  • using reduce() Function

Insert Element to Front of List Using insert() Method

The insert() method in Python generally inserts the element at any position in the list and also performs the necessary shifts required internally and hence can also be used to perform this very task. 

Python3




# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using insert() to append
# at beginning. append 6
test_list.insert(0, 6)
          
# printing resultant list
print("Resultant list is: " + str(test_list))


Output:

Original list: [1, 3, 4, 5, 7]
Resultant list is: [6, 1, 3, 4, 5, 7]

Time Complexity: O(n), where n is the number of elements in the list. This is because the insert method has to shift all the elements of the list to accommodate the newly inserted element, which takes O(n) time.
Auxiliary Space: O(1), as the insert method does not require any additional memory to be allocated.

Insert Element to Front of List Using [ ] and + Operator

The square brackets [] and the + Arithmetic operator can be combined to perform this task. We convert the element to a list in Python and then perform the list concatenation operation. 

Python3




# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using [] and + to append
# at beginning append 6
test_list = [6] + test_list
          
# printing resultant list
print("Resultant list is: " + str(test_list))


Output

Original list: [1, 3, 4, 5, 7]
Resultant list is: [6, 1, 3, 4, 5, 7]

Time complexity: O(n)
Auxiliary space: O(n) where n is the length of the list.

Append integer to the beginning of the list in Python using List Slicing

List Slicing is also another method to perform this particular task. We just assign the 0th sliced list to the list converted from the element. This does the trick and is quite elegant. 

Python3




# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using slicing to append
# at beginning. append 6
test_list[:0] = [6]
          
# printing resultant list
print("Resultant list is: " + str(test_list))


Output

Original list: [1, 3, 4, 5, 7]
Resultant list is: [6, 1, 3, 4, 5, 7]

Time Complexity: O(n), where n is the number of elements in the list.
Auxiliary Space: O(1), as no additional space is used to store the elements.

Append Integer to the Beginning of list using Collections.deque.appendleft()

The Python list can be converted to deque using the dequeue() function of the collections module and then the appendleft() function can be used to perform the push-like operation from the front of the double-ended queue. 

Python3




# Python3 code to demonstrate
# to add element at beginning
# using collections.deque.pushleft()
from collections import deque
 
# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using collections.deque.pushleft()
# to append at beginning
# append 6
test_list = deque(test_list)
test_list.appendleft(6)
test_list = list(test_list)
          
# printing resultant list
print("Resultant list is: " + str(test_list))


Output

Original list: [1, 3, 4, 5, 7]
Resultant list is: [6, 1, 3, 4, 5, 7]

Time complexity: O(1)
Auxiliary space: O(1)

Append Integer to Beginning of List Using Extend() Method

In this method, we will convert the element to be appended to a list in Python and then extend this list with the list to which we want to add the element using the extend() function.

Python3




# Python3 code to demonstrate
# to add element at beginning
 
# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
x=[6]
x.extend(test_list)
         
# printing resultant list
print("Resultant list is: " + str(x))


Output

Original list: [1, 3, 4, 5, 7]
Resultant list is: [6, 1, 3, 4, 5, 7]

Time Complexity: O(n), where n is the length of the original list.
Auxiliary Space: O(n), as a new list is created which is equal in length to the original list.

Append Integer to Beginning of List Using List() and itertools.chain() Functions

Here we will use the chain() function of the itertools module to combine the element and the list and then convert it to a list using the list() method.

Python3




# Python3 code to demonstrate
# to add element at beginning
# using itertools
import itertools
 
# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# using itertools to append
# at beginning. append 6
test_list = list(itertools.chain([6], test_list))
         
# printing resultant list
print("Resultant list is: " + str(test_list))


Output

Original list: [1, 3, 4, 5, 7]
Resultant list is: [6, 1, 3, 4, 5, 7]

Time Complexity: O(n), where n is the length of the original list because the entire list has to be copied to a new list with the additional element at the beginning.

Auxiliary Space: O(n+1), where n is the length of the original list because a new list is created to store the modified list.

Append Integer to Beginning of List Using Numpy.concatenate() Function

We can also add an element to the front of the list by converting it to a Python numpy array using the numpy.array() function. Then we will use numpy.concatenate() method and pass the element and the list to it as parameters. Finally, convert it back to the list using the tolist() function in Python.

Python3




import numpy as np
 
# initializing list
test_list = [1, 3, 4, 5, 7]
 
# printing initial list
print("Original list: " + str(test_list))
 
# element to be added
element = 6
 
# convert the input list to a numpy array
arr = np.array(test_list)
 
# create a numpy array of the element to be added
arr_elem = np.array([element])
 
# concatenate both arrays along the first dimension
concatenated_arr = np.concatenate((arr_elem, arr), axis=0)
 
# convert the concatenated array back to a list
result_list = concatenated_arr.tolist()
 
# printing resultant list
print("Resultant list is: " + str(result_list))


Output

Original list : [1, 3, 4, 5, 7]
Resultant list is : [6, 1, 3, 4, 5, 7]

Time Complexity: O(n), where n is the number of elements in the list. The time complexity is dominated by the conversion of the list to a numpy array and back to a list.
Auxiliary Space: O(n), as we are creating a numpy array to store the element to be added.

Append Integer to Beginning of List Using Reduce() Function

In this method, we will use the reduce() function of the functools module which takes two parameters. The first parameter is a lambda function which takes two lists as input and returns their concatenation. The second parameter is a list containing an empty list and the input list. The lambda function concatenates the two lists, placing the first list (containing the element to be added) at the beginning of the result.

Python3




from functools import reduce
 
# Initializing list
test_list = [1, 3, 4, 5, 7]
 
# Printing initial list
print("Original list: ", test_list)
 
# Using reduce() function to insert an element at the beginning of the list
test_list = reduce(lambda x, y: [6] + x + y, [[], test_list])
 
# Printing the resultant list
print("Resultant list: ", test_list)


Output

Original list : [1, 3, 4, 5, 7]
Resultant list is : [6, 1, 3, 4, 5, 7]

Time Complexity: 
– The `reduce()` function has a time complexity of O(n), where n is the number of elements in the list. This is because `reduce()` applies the lambda function to each pair of elements in the list until a single result is obtained.
– In our case, we are concatenating two lists containing a total of n elements, so the time complexity is O(n).

Auxiliary Space: 
– The space complexity of the `reduce()` function depends on the size of the input list and the size of the lambda function.
– In our case, we are using a lambda function that concatenates two lists. Since the size of the input list and the size of the lambda function are both O(n), the space complexity is O(n). This is because the lambda function creates a new list in memory for each pair of lists that it concatenates, so the space required is proportional to the size of the input list.

RELATED ARTICLES

Most Popular

Recent Comments