Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i append in reverse? python

Tags:

python

.append Function adds elements to the list. How can I add elements to the list? In reverse? So that index zero is new value, and the old values move up in index? What append does

[a,b,c,d,e]

what I would like.

[e,d,c,b,a]

Thank you very much.

like image 200
Web Master Avatar asked Jun 12 '12 22:06

Web Master


People also ask

Does append add to front or back Python?

append() : append the element to the end of the list. insert() : inserts the element before the given index.

Does append add to front or back of list?

The difference between the two methods is that . append() adds an item to the end of a list, whereas . insert() inserts and item in a specified position in the list.

What does append () do in Python?

The append() method appends an element to the end of the list.

Is there a reverse command in Python?

There is no built-in function to reverse a String in Python.


2 Answers

Suppose you have a list a, a = [1, 2, 3]

Now suppose you wonder what kinds of things you can do to that list:

dir(a)

Hmmmm... wonder what this insert thingy does...

help(a.insert)

Insert object before index, you say? Why, that sounds a lot like what I want to do! If I want to insert something at the beginning of the list, that would be before index 0. What object do I want to insert? Let's try 7...

a.insert(0, 7)
print a

Well, look at that 7 right at the front of the list!

TL;DR: dir() will let you see what's available, help() will show you how it works, and then you can play around with it and see what it does, or Google up some documentation since you now know what the feature you want is called.

like image 137
kindall Avatar answered Oct 04 '22 16:10

kindall


It would be more efficient to use a deque(double-ended queue) for this. Inserting at index 0 is extremely costly in lists since each element must be shifted over which requires O(N) running time, in a deque the same operation is O(1).

>>> from collections import deque
>>> x = deque()
>>> x.appendleft('a')
>>> x.appendleft('b')
>>> x
deque(['b', 'a'])
like image 37
jamylak Avatar answered Oct 04 '22 17:10

jamylak