1

I tried to work with a list of deques and was not able to to append a value to a single deque by indexing it. It looks like the following:

>>> l_deque = [deque([0] * 3, maxlen = 3)] * 5
>>> l_deque
[deque([0, 0, 0]),
 deque([0, 0, 0]),
 deque([0, 0, 0]),
 deque([0, 0, 0]),
 deque([0, 0, 0])]

>>> l_deque[0]
deque([0, 0, 0])

So far so good. But when I try to append a value to a single deque it appends it to every deque:

>>> l_deque[0].append(1)
>>> l_deque
[deque([0, 0, 1]),
 deque([0, 0, 1]),
 deque([0, 0, 1]),
 deque([0, 0, 1]),
 deque([0, 0, 1])]

I expected something like this:

[deque([0, 0, 1]),
 deque([0, 0, 0]),
 deque([0, 0, 0]),
 deque([0, 0, 0]),
 deque([0, 0, 0])]

Do you have an idea where I took the wrong turn? Thanks

Edit: Thanks guys, Changing it to

    >>> l = [deque([0] * 3, maxlen = 3), 
            deque([0] * 3, maxlen = 3), 
            deque([0] * 3, maxlen = 3), 
            deque([0] * 3, maxlen = 3), 
            deque([0] * 3, maxlen = 3)]

did the job. Ugly but effective.

  • Classic. When you do `[x] * 5` you create a list `[x, x, x, x, x]` where every `x` point to the same place in memory, if `x` is a referenced object like `deque`. So when you modify one of your deques you modify all of them. – VisioN Aug 21 '20 at 08:57
  • `[deque([0] * 3, maxlen = 3)] * 5` creates a list with *five references to the same deque object*. – juanpa.arrivillaga Aug 21 '20 at 08:59
  • 1
    @VisioN I'm not sure what you mean by "a referenced object like deque", but I think it is important to be clear that this behavior is the same *for all objects*, i.e. *for anything* in Python. – juanpa.arrivillaga Aug 21 '20 at 09:00
  • @juanpa.arrivillaga That doesn't work this way for primitives, e.g. `[0] * 3` will create a list of integer objects by value. – VisioN Aug 21 '20 at 09:03
  • `[deque([0] * 3, maxlen=3) for _ in range(5)]` for a less ugly solution… – deceze Aug 21 '20 at 09:07
  • @VisioN no, that is not true. There **is no such thing as primitive values in Python**. *Everything is an object*. the `int` object created by the literal `1000` is *an object in the exact same way a `list` is an object*. Python doesn't distinguish between "reference types and value types" like Java, Python is a purely object-oriented language. Indeed, just prove it to yourself: `set(map(id, [1000]*5))` – juanpa.arrivillaga Aug 21 '20 at 09:13

0 Answers0