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

18

60

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?

Heighho answered 5/8, 2008 at 7:18 Comment(0)
R
36

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.

Ridenour answered 5/8, 2008 at 13:22 Comment(0)
D
23

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.

Debase answered 5/8, 2008 at 7:27 Comment(1)
for which operations are tuple faster? indexing?Totaquine
U
12

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.

Understructure answered 7/8, 2008 at 11:21 Comment(1)
With the subtle caveat that a tuple must contain only other immutables to be considered hashable, e.g.: ([], 3) is not hashable; ("hi", 3) is hashable; ( ([], 3), 3) is not hashable; ( ((), 3), 3) is hashable.Fruiter
W
8

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 :'(
    
Wingspread answered 15/8, 2008 at 18:0 Comment(0)
D
5

[1, 2, 3] is a list in which one can add or delete items.
(1, 2, 3) is a tuple in which once defined, modification cannot be done.

Duplex answered 25/6, 2011 at 11:14 Comment(0)
S
4

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.

Spokeshave answered 15/8, 2008 at 16:38 Comment(0)
S
3

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.

Stunner answered 8/8, 2008 at 6:6 Comment(0)
A
3

open a console and run python. Try this:

  >>> list = [1, 2, 3]     
  >>> dir(list)
    ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delsli
    ce__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getit
    em__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
     '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__r
    educe__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__'
    , '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 
'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

As you may see the last on the last line list have the following methods: 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'

Now try the same for tuple:

>>> tuple = (1, 2, 3)
>>> dir(tuple)
    ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__
    format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__get
    slice__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__
    lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__'
    , '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']

Only 'count' and 'index' from list methods appears here.

This is because tuples are immutable and they don't support any modifications. Instead they are simpler and faster in internal implementation.

Althaalthea answered 10/10, 2015 at 19:30 Comment(1)
On python 3: sorted(x for x in set(dir(list)).difference(dir(tuple)) if not x.startswith('_')) >>> ['append', 'clear', 'copy', 'extend', 'insert', 'pop', 'remove', 'reverse', 'sort']Unreal
O
3
  • A tuple might represent a key in dictionary, because it's immutable.
  • Use lists if you have a collection of data that doesn't need random access.
Opalescent answered 20/5, 2017 at 7:30 Comment(0)
M
2

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.

Mok answered 8/8, 2008 at 6:48 Comment(0)
H
2

[1,2,3] is a list.

(1,2,3) is a tuple and immutable.

Homely answered 8/10, 2014 at 6:2 Comment(0)
B
2

(1,2,3) and [1,2,3] can be used interchangeably in rare conditions.

So (1,2,3) is a tuple and is immutable. Any changes you wish to make need to overwrite the object.

[1,2,3] is a list and elements can be appended and removed.

List has more features than a tuple.

Bernitabernj answered 31/3, 2018 at 9:14 Comment(0)
A
1

In simple words, lists are mutable whereas tuples are not. Hence, if you want to modify the elements in your program i.e., adding, deleting or altering elements, go for a list. But, if you don't want tat to happen i.e., may be for setting sequence in for loop, etc. go for a tuple

Achates answered 19/8, 2020 at 4:14 Comment(0)
G
0

(1,2,3) is a tuple while [1,2,3] is a list. A tuple is an immutable object while a list is mutable.

Gwenni answered 19/2, 2016 at 2:15 Comment(0)
A
0

(1,2,3) is a tuple and [1,2,3] is a list. You either of the two represent sequences of numbers but note that tuples are immutable and list are mutable Python objects.

Amadou answered 27/6, 2016 at 20:48 Comment(0)
P
0

(1,2,3)-tuple [1,2,3]-list lists are mutable on which various operations can be performed whereas tuples are immutable which cannot be extended.we cannot add,delete or update any element from a tuple once it is created.

Paramagnet answered 7/2, 2019 at 10:3 Comment(0)
A
0

a = (1,2,3) is a tuple which is immutable meaning you can't add anything into a b = [1,2,3] is a list in python which is immutable meaning you can make changes into 'b' either delete or add numbers into it.

Ameba answered 21/6, 2020 at 20:14 Comment(0)
F
0

(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.

Flipper answered 8/10, 2021 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.