tags:

views:

451

answers:

8

In many places,(1,2,3) and [1,2,3] can be used interchangably.

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

+14  A: 

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.

EDIT: fixed spelling and added links to diveintopython.org

sparkes
+14  A: 

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.

Joe Shaw
+7  A: 

Tuples are a quick\flexible way to create composite data-types. Lists are containers for, well, lists of objects.

For example, you would use a List to store a list of student details in a class.

Each student detail in that list may be a 3-tuple containing their roll number, name and test score.

 `[(1,'Mark',86),(2,'John',34)...]`

Also, because tuples are immutable they can be used as keys in dictionaries.

HS
+1  A: 

As others have mentioned, Lists and tuples are both containers which can be used to store python objects. Lists are extensible and their contents can change by assignment, on the other hand tuples are immutable.

Also, lists cannot be used as keys in a dictionary whereas tuples can.

JSN
+1  A: 

If you can find a solution that works with tuples, use them, as it forces immutability which kind of drives you down a more functional path. You almost never regret going down the functional/immutable path.

Michael Neale
+2  A: 

Whenever I need to pass in a collection of items to a function, if I want the function to not change the values passed in - I use tuples.

Else if I want to have the function to alter the values, I use list.

Always if you are using external libraries and need to pass in a list of values to a function and are unsure about the integrity of the data, use a tuple.

cnu
+6  A: 

The notion of tuples are highly expressive:

  • Pragmatically, they are great for packing and unpacking values (x,y=coord).

  • In combination with dictionaries (hash tables), they allow forms of mapping that would otherwise require many levels of association. For example, consider marking that (x,y) has been found.

    // PHP
    if (!isset($found[$x])) {
        $found[$x] = Array();
        $found[$x][$y] = true;
    } else if (!isset($found[$x][$y])) {
        $found[$x][$y] = true;
    }
    
    
    # Python
    found[(x,y)] = True # parens added for clarity
    
  • Lists should be used with the expectation of operations on its contents (hence the various mentions of immutability). One will want to pop, push, splice, slice, search, insert before, insert after, etc with a list.

  • Tuples should be a low-level representation of an object, where simple comparisons are made, or operations such as extracting the n'th element or n elements in a predictable fashion, such as the coordinates example given earlier.

  • Lastly, lists are not hashable, so the type of mapping done with dictionaries (hash tables in Perl, associative arrays in PHP) must be done with tuples.

    Here's a simple example of tuples and dictionaries, together at last:

    """
    couple is a tuple of two people
    doesLike is a dictionary mapping couples to True or False
    """
    couple = "john", "jane"
    doesLike = dict()
    doesLike[couple] = True
    doesLike["jane", "john"] = False # unrequited love :'(
    
jcsalterego
+1  A: 

@statictypeorg

Also, because tuples are immutable they can be used as keys in dictionaries.

With the subtle caveat that a tuple must contain only other immutables to be considered hashable, e.g.:

([], 3) # not hashable

("hi", 3) # hashable

( ([], 3), 3) # not hashable

( ((), 3), 3) # hashable

Jegschemesch