Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: what is the difference between (1,2,3) and [1,2,3], and when should I use each?

In many places, (1,2,3) (a tuple) and [1,2,3] (a list) can be used interchangeably.

When should I use one or the other, and why?

like image 580
Mark Harrison Avatar asked Aug 05 '08 07:08

Mark Harrison


People also ask

What is the difference between 123 and 123 in Python?

(1,2,3) is immutable, so you can't add to it or change one of the items. In contrast, [1,2,3] is mutable, so you can add to it or change the items.

What does 1 :] mean in Python?

So A[1:] is the slice notation that says, "Take elements 1 to the end" of the list. So in my simple example A[1:] gives you a slice of the list that is [4,5,6]

What is the difference between a * 3 and A A A?

Difference(if any) between a*3 and (a,a,a). The difference is that a*3 repeats the elements for 3 times in the given order as a whole and encloses them into the given iterable, i.e., tuple. While (a, a, a) is nothing but the enclosing of iterables, i.e., tuples a - as it is - into a new tuple.


2 Answers

From the Python FAQ:

Lists and tuples, while similar in many respects, are generally used in fundamentally different ways. Tuples can be thought of as being similar to Pascal records or C structs; they're small collections of related data which may be of different types which are operated on as a group. For example, a Cartesian coordinate is appropriately represented as a tuple of two or three numbers.

Lists, on the other hand, are more like arrays in other languages. They tend to hold a varying number of objects all of which have the same type and which are operated on one-by-one.

Generally by convention you wouldn't choose a list or a tuple just based on its (im)mutability. You would choose a tuple for small collections of completely different pieces of data in which a full-blown class would be too heavyweight, and a list for collections of any reasonable size where you have a homogeneous set of data.

like image 101
Joe Shaw Avatar answered Sep 20 '22 01:09

Joe Shaw


The list [1,2,3] is dynamic and flexible but that flexibility comes at a speed cost.

The tuple (1,2,3) is fixed (immutable) and therefore faster.

like image 28
sparkes Avatar answered Sep 19 '22 01:09

sparkes