Don't forget to also checkout my second blog containing articles to all other related ICT topics!!

Wednesday, May 9, 2012

Use collections deque for very fast pop and append operations


from collections import deque

#deque offers very fast append and pop operations on either side.
#So if performance matters and these are the operations that occur often, choose deque
deck = deque(['a','y','t','h', 'o', 'z'])
print deck
deck.popleft()
print deck
deck.pop()
print deck
deck.appendleft('p')
print deck
deck.append('n')
print deck
print ''.join(deck) + ' rocks'

deque(['a', 'y', 't', 'h', 'o', 'z'])
deque(['y', 't', 'h', 'o', 'z'])
deque(['y', 't', 'h', 'o'])
deque(['p', 'y', 't', 'h', 'o'])
deque(['p', 'y', 't', 'h', 'o', 'n'])
python rocks

No comments:

Post a Comment