Let's say I have these assignments:
points = [] point = (1, 2)
How come when I do this:
points += point
It works completely fine, and gives me points = [1, 2]. However, If I do something like:
points = points + point
It gives me a TypeError: can only concatenate list (not "tuple") to list. Aren't these statements the same thing, though?
List and Tuple in Python are the classes of Python Data Structures. The list is dynamic, whereas the tuple has static characteristics. This means that lists can be modified whereas tuples cannot be modified, the tuple is faster than the list because of static in nature.
One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.
The length of a tuple is fixed, whereas the length of a list is variable. Therefore, lists can have a different sizes, but tuples cannot. Tuples are allocated large blocks of memory with lower overhead than lists because they are immutable; whereas for lists, small memory blocks are allocated.
Tuples are identical to lists in all respects, except for the following properties: Tuples are defined by enclosing the elements in parentheses ( () ) instead of square brackets ( [] ). Tuples are immutable.
The difference, is that list +=
is equivalent to list.extend()
, which takes any iterable and extends the list, it works as a tuple is an iterable. (And extends the list in-place).
On the other hand, the second assigns a new list to points
, and attempts to concatenate a list to a tuple, which isn't done as it's unclear what the expected results is (list or tuple?).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With