Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Deque appendleft with list

Tags:

python

list

deque

I am currently creating my deque object using the following,

self.CommandList = deque((['S', False, 60],['c'],['g16'],['i50'],['r30', True],['u320'],['o5000'],['b1'],['B4500'],['W1'],['l5154'],['!10'],['p2', True, 10],['e1'],['K20'],['U0'],['Y0']))

But I wish to add a similar list to the queue later but using appendleft, so it can jump ahead of the list. I assumed the following, but had no luck.

NewList = (['S'],['c'],['!10'],['p4'],['o1200'],['i50'],['r30'],['b10'],['d1'],['A', True, 163])
self.CommandList.appendleft(NewList)

Is this even possible with appendleft?

like image 443
Schodemeiss Avatar asked Jul 15 '10 14:07

Schodemeiss


People also ask

Is deque more efficient than list?

In terms of efficiency, ArrayDeque is more efficient than the LinkedList for add and remove operation at both ends. The best operation in a LinkedList implementation is removing the current element during the iteration.

Is deque a list in Python?

As you learned earlier, deque is implemented as a doubly linked list. So, every item in a given deque holds a reference (pointer) to the next and previous item in the sequence. Doubly linked lists make appending and popping items from either end light and efficient operations.

Can you iterate through a deque Python?

Deque objects support indexing and iteration, so we can iterate over a queue as if we were iterating over a list.


1 Answers

I think you want .extendleft here. This will "extend the list" instead of just appending the list as one element.

z = collections.deque([1,2,3,4])   # [1, 2, 3, 4]

z.appendleft(['bad', 'news'])   # [ ['bad', 'news'], 1, 2, 3, 4 ]
z.extendleft(['good', 'news'])  # [ 'good', 'news', ['bad', 'news'], 1, 2, 3, 4 ]

If they are getting inserted in reverse, the quick fix is to just reverse the list:

z.extendleft(reversed(['good', 'news']))
like image 185
Donald Miner Avatar answered Sep 21 '22 07:09

Donald Miner