简体   繁体   中英

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.

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.

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

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)

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.

You can do

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

But the insert method works as well.

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

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)

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

your_list = [x] + your_list

or:

your_list.insert(0, x)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM