- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Append at front and remove from rear in Python
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
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
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'])
Advertisements