Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List += Tuple vs List = List + Tuple

Tags:

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?

like image 969
Richard Chu Avatar asked Nov 11 '12 16:11

Richard Chu


People also ask

What is tuple difference between list and tuple?

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.

Are tuples and lists the same?

One of the most important differences between a list and a tuple is that list is mutable, whereas a tuple is immutable.

What are two differences between lists and tuples?

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.

Is a tuple a list of lists?

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.


1 Answers

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?).

like image 145
Gareth Latty Avatar answered Nov 17 '22 12:11

Gareth Latty