3
msg = 'afdssav'
MYQ = deque(msg)
MYPQ.append('asdf')

Here I am trying to create a deque of strings, however when I pop elements or try to read elements from it using Python 2.7 I get char by char instead.

How can I make it such that it would return the strings the same way I insert them?

i.e. I want MYQ[1] to be 'asdf' and MYQ.pop() to return msg.

1
  • 1
    that's because a string is iterable. Commented Apr 18, 2014 at 14:08

1 Answer 1

5

Probably like this:

MYQ = deque([msg])

Demo:

In [1]: from collections import deque

In [2]: msg = 'afdssav'

In [3]: myq = deque([msg])

In [4]: myq.append('asdf')

In [5]: myq
Out[5]: deque(['afdssav', 'asdf'])

The call signature of deque is:

deque([iterable[, maxlen]]) --> deque object

Strings are iterable, but when you iterate over a string, you get single characters. Hence the behavior you see:

In [7]: deque(msg)
Out[7]: deque(['a', 'f', 'd', 's', 's', 'a', 'v'])

You want to give deque an iterable that would produce the entire string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.