Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistent behavior concatenating lists and tuples in python

I noticed a surprising behavior when trying to concatenate lists and tuples.

Usually, they don't mix:

(0, 1) + [2, 3]

results in:

TypeError: can only concatenate tuple (not "list") to tuple

and, vice versa

[0, 1] + (2, 3)

gives:

TypeError: can only concatenate list (not "tuple") to list

So far, nothing was unexpected. However, if you use a variable assignment via "+=", the behavior for lists changes!

l = [0, 1]
l += (2, 3)
l

gives

[0, 1, 2, 3]

But not for tuples:

t = (0, 1)
t += [2, 3]
t

still produces an error:

TypeError: can only concatenate tuple (not "list") to tuple

Of course, there is no practical problem here, but I'm curious: What's going on there?

like image 765
Ansgar T. Avatar asked May 30 '19 13:05

Ansgar T.


People also ask

Can tuples be concatenated together?

Operators can be used to concatenate or multiply tuples. Concatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple.

Can lists in python be concatenated?

Python's extend() method can be used to concatenate two lists in Python. The extend() function does iterate over the passed parameter and adds the item to the list thus, extending the list in a linear fashion. All the elements of the list2 get appended to list1 and thus the list1 gets updated and results as output.

What is concatenation of list in python?

Concatenation of lists is an operation where the elements of one list are added at the end of another list. For example, if we have a list with elements [1, 2, 3] and another list with elements [4, 5, 6] .


1 Answers

+= for lists doesn't expect an actual list as its right-hand operand; it will accept any iterable value. It is effectively an operator version of list.extend (which also accepts an arbitrary iterable value).

tuple doesn't define __iadd__ at all, so t += [2, 3] is just syntactic sugar for t = t + [2,3], and we've already confirmed that tuple.__add__ can't add a tuple and a list together.

like image 134
chepner Avatar answered Nov 10 '22 09:11

chepner