Append at front and remove from rear in Python

PythonServer Side ProgrammingProgramming

When using Python for data manipulation we frequently and remove elements from list. There are methods which can do this effectively and python provides those function as part of standard library as well as part of external library. We import the external library and use it for this addition and removal of elements. Below we will see two such approaches.

Using + operator

Example

 Live Demo

values = ['Tue','wed','Thu','Fri','Sat','Sun']
print("The given list : " ,values)
#here the appending value will be added in the front and popping the element from the end.
result = ['Mon'] + values[:-1]
print("The values after appending and popping : " + str(result))

Running the above code gives us the following result:

The given list : ['Tue', 'wed', 'Thu', 'Fri', 'Sat', 'Sun']
The values after appending and popping : ['Mon', 'Tue', 'wed', 'Thu', 'Fri', 'Sat']

Using dequeuer from collections

In this method we use a double ended queue. It has functions like appendleft and appendright and also it has pop method. We use them to add an element at the left end and remove an element from the right end.

Example

 Live Demo

import collections
a = collections.deque( ['Tue','wed','Thu','Fri','Sat','Sun'])
print('Original List: ',a)
a.appendleft('Mon')
a.pop()
print('New list: ',a)

Running the above code gives us the following result:

Original List: deque(['Tue', 'wed', 'Thu', 'Fri', 'Sat', 'Sun'])
New list: deque(['Mon', 'Tue', 'wed', 'Thu', 'Fri', 'Sat'])
raja
Published on 02-Jan-2020 09:41:23
Advertisements