4 ms·
this list is awesome. made my morning. anyone know why this works in python lst=[] lst+=2, # note , in the end print(lst) #[2]
by dominotw 4y ago
this list is awesome. made my morning.
anyone know why this works in python
lst=[]
lst+=2, # note , in the end
print(lst) #[2]
- HelloNurse 4y agoThe tuple is sequence-like enough to be concatenated with a list: []+(2,) differs from []+[2] only by the type of the temporary object that contains 2.
- klyrs 4y agoThe truly weird thing here is that [] + (2,) is a TypeError: can only concatenate list (not "tuple") to list but L = [] L += (2,) is totally cool. In the end, it makes sense because I can't tell you if []+() should be a tuple or a list, and even if I did, I might have a different answer for ()+[]; whereas L+=bla looks like the type of L should not change.
- maleldil 4y agoThey're different operations. The first is concatenation; the second is extension. Concatenation only works with other lists, but extension works with any iterable.
- carapace 4y agoThe comma operator makes tuples. lst += (2,)
- raymondh 4y agoRoughly, that is true. However, the actual pattern matching rules are a bit more complex: () # Makes a zero-tuple. The parens are required. 2, # Makes a one-tuple. (2,) # Makes a one-tuple. The parens are optional. [2] # Makes a list of size one. [(2)] # Also makes a list of size one. [2,] # Also makes a list of size one. f(x, y) # Call a function with two arguments. f((x, y)) # Make a 2-tuple and call a function with one argument.
- carapace 4y agoYeah, you're right, of course. I should have mentioned the concept of "comma operator" is a heuristic, not something from the grammar or semantics. BTW, kind of a tangent, I've always assumed (but not checked) that every "()" literal evaluates to one singleton zero-tuple, do you know if that's true?
- raymondh 4y agoIt was, but that is not guaranteed and may stop being true due to work on subinterpreters, new memory managers, and heap types. Also, it used to be true that ``frozenset() is frozenset()``, but that was lost in the war on singletons and global state.
- carapace 4y agoAh, cheers! You're a treasure!