1

Why is it that I get "TypeError: can only concatenate list (not "dict") to list" when I do this:

print([1,2,3] + {-i:i*i for i in range(3)})

But this:

a = [1,2,3]
a += {-i-1:0 for i in range(3)}
print(a)

Runs as it ok and outputs this:

[1, 2, 3, -1, -2, -3]
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Rustam A.
  • 809
  • 8
  • 15
  • 4
    Because `+=` is basically `.extend`, and accepts any iterable. – jonrsharpe Oct 14 '20 at 16:25
  • Is there any particular reason why the list prefers the dictionary keys over the dictionary values? – dee cue Oct 14 '20 at 16:32
  • 4
    `a += x` implicitly calls `iter(x)`, and the keys are what the default iterator for a `dict` returns. It's just a design choice. If you wanted the values, you'd have to be explicit: `a += d.values()`. – chepner Oct 14 '20 at 16:34
  • 3
    @deecue in Python, when a dict is treated as an iterable, it returns its keys. https://docs.python.org/3/tutorial/datastructures.html#dictionaries https://docs.python.org/3/library/stdtypes.html#mapping-types-dict – Boris Verkhovskiy Oct 14 '20 at 16:35
  • Thank you all for pointing out the answer so quickly! – Rustam A. Oct 14 '20 at 22:22

0 Answers0