Web Master
Web Master

Reputation: 4340

how can i append in reverse? 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.

Upvotes: 5

Views: 45001

Answers (8)

Shivam Yadav
Shivam Yadav

Reputation: 21

lst=["a","b","c","d","e","f"]
lst_rev=[]
lst_rev.append(lst[::-1])
print(lst_rev)

Upvotes: 2

Hakan
Hakan

Reputation: 13

Here's an example of how to add elements in a list in reverse order:

liste1 = [1,2,3,4,5]
liste2 = list()
for i in liste1:
    liste2.insert(0,i)

Upvotes: 1

Fethi Dilmi
Fethi Dilmi

Reputation: 161

Use the following (assuming x is what you want to prepend):

your_list = [x] + your_list

or:

your_list.insert(0, x)

Upvotes: 0

Dan Breen
Dan Breen

Reputation: 12934

Using Python's list insert command with 0 for the position value will insert the value at the head of the list, thus inserting in reverse order:

your_list.insert(0, new_item)

Upvotes: 6

jamylak
jamylak

Reputation: 133634

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'])

Upvotes: 12

kindall
kindall

Reputation: 184280

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.

Upvotes: 21

user1357159
user1357159

Reputation: 319

You can do

your_list=['New item!!']+your_list

But the insert method works as well.

Upvotes: 2

cdhowie
cdhowie

Reputation: 169183

Use somelist.insert(0, item) to place item at the beginning of somelist, shifting all other elements down. Note that for large lists this is a very expensive operation. Consider using deque instead if you will be adding items to or removing items from both ends of the sequence.

Upvotes: 5

Related Questions