Difference between Lists and tuples in Python

What's the difference?

What are the advantages / disadvantages of tuples / lists?


Apart from tuples being immutable there is also a semantic distinction that should guide their usage. Tuples are heterogeneous data structures (i.e., their entries have different meanings), while lists are homogeneous sequences. Tuples have structure, lists have order.

Using this distinction makes code more explicit and understandable.

One example would be pairs of page and line number to reference locations in a book, e.g.:

my_location = (42, 11)  # page number, line number

You can then use this as a key in a dictionary to store notes on locations. A list on the other hand could be used to store multiple locations. Naturally one might want to add or remove locations from the list, so it makes sense that lists are mutable. On the other hand it doesn't make sense to add or remove items from an existing location - hence tuples are immutable.

There might be situations where you want to change items within an existing location tuple, for example when iterating through the lines of a page. But tuple immutability forces you to create a new location tuple for each new value. This seems inconvenient on the face of it, but using immutable data like this is a cornerstone of value types and functional programming techniques, which can have substantial advantages.

There are some interesting articles on this issue, e.g. "Python Tuples are Not Just Constant Lists" or "Understanding tuples vs. lists in Python". The official Python documentation also mentions this ("Tuples are immutable, and usually contain an heterogeneous sequence ...").

In a statically typed language like Haskell the values in a tuple generally have different types and the length of the tuple must be fixed. In a list the values all have the same type and the length is not fixed. So the difference is very obvious.

Finally there is the namedtuple in Python, which makes sense because a tuple is already supposed to have structure. This underlines the idea that tuples are a light-weight alternative to classes and instances.

If you went for a walk, you could note your coordinates at any instant in an (x,y) tuple.

If you wanted to record your journey, you could append your location every few seconds to a list.

But you couldn't do it the other way around.

Difference between list and tuple

  1. Size
    a = tuple(range(1000))
    b = list(range(1000))
    a.__sizeof__() # 8024
    b.__sizeof__() # 9088

    Due to the smaller size of a tuple operation with it a bit faster but not that much to mention about until you have a huge amount of elements.

  2. Permitted operations
    b    = [1,2]
    b[0] = 3       # [3, 2]
    a    = (1,2)
    a[0] = 3       # Error

    that also mean that you can't delete element or sort tuple. At the same time you could add new element to both list and tuple with the only difference that you will change id of the tuple by adding element

    a     = (1,2)
    b     = [1,2]  
    id(a)          # 140230916716520
    id(b)          # 748527696
    a   += (3,)    # (1, 2, 3)
    b   += [3]     # [1, 2, 3]
    id(a)          # 140230916878160
    id(b)          # 748527696
  3. Usage

    You can't use list as a dictionary identifier

    a    = (1,2)
    b    = [1,2] 
    c = {a: 1}     # OK
    c = {b: 1}     # Error

The key difference is that tuples are immutable. This means that you cannot change the values in a tuple once you have created it.

So if you're going to need to change the values use a List.

Benefits to tuples:

  1. Slight performance improvement.
  2. As a tuple is immutable it can be used as a key in a dictionary.
  3. If you can't change it neither can anyone else, which is to say you don't need to worry about any API functions etc. changing your tuple without being asked.

Lists are mutable; tuples are not.

From docs.python.org/2/tutorial/datastructures.html

Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures.

Lists are for looping, tuples are for structures i.e. "%s %s" %tuple.

Lists are usually homogeneous, tuples are usually heterogeneous.

Lists are for variable length, tuples are for fixed length.

It's been mentioned that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline, some libraries actually behave differently based on what they are passed. Take numpy for example (copied from another post where I ask for more examples):

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

Point is, while numpy may not be part of the standard library, it's a major python library, and within numpy lists and tuples are completely different things.

The values of list can be changed any time but the values of tuples can't be change.

The advantages and disadvantages depends upon the use. If you have such a data which you never want to change then you should have to use tuple, otherwise list is the best option.

List is mutable and tuples is immutable. The main difference between mutable and immutable is memory usage when you are trying to append an item.

When you create a variable, some fixed memory is assigned to the variable. If it is a list, more memory is assigned than actually used. E.g. if current memory assignment is 100 bytes, when you want to append the 101th byte, maybe another 100 bytes will be assigned (in total 200 bytes in this case).

However, if you know that you are not frequently add new elements, then you should use tuples. Tuples assigns exactly size of the memory needed, and hence saves memory, especially when you use large blocks of memory.

Category: python Time: 2009-03-09 Views: 0

Related post

  • Difference between __str__ and __repr__ in Python 2009-09-17

    What is the difference between __str__ and __repr__ in Python? --------------Solutions------------- Alex summarized well but, surprisingly, was too succinct. First, let me reiterate the main points in Alex's post: The default implementation is useles

  • Differences between isinstance() and type() in python 2009-10-11

    What are the differences between these two code fragments? Which way is considered to be more pythonic? Using type(): import types if type(a) is types.DictType: do_something() if type(b) in types.StringTypes: do_something_else() Using isinstance(): i

  • What is the major difference between list of tuples and a dictionary? 2016-01-27

    For example: a = (1,2,3) b= (5,6,7) c=zip(a,b) [(1,5),(2,6),(3,7)] A dictionary would have {1:5, 2:6, 3:7} --------------Solutions------------- A dictionary is a datastructure that is fundamentally based on a hash table, which means that when you loo

  • Difference between returns and printing in python? 2010-10-07

    This question already has an answer here: How is returning the output of a function different than printing it? 4 answers In python I don't seem to be understanding the return function. Why use it when I could just print it? def maximum(x, y): if x >

  • Lists and tuples in Python function arguments 2016-01-26

    This question already has an answer here: Unpack a list in Python? 2 answers I'm using the SciPy function kruskal to investigate a statistical database. The SciPy function takes a number of lists as arguments: from scipy.stats import kruskal kruskal(

  • Difference between list and library 2012-10-30

    I have gone through lots of articles on internet and finally decided to ask a question here to all experts. -- Edits -- I noticed, I can manage event receivers in both almost same way I can create folders in both I can add custom fields, site columns

  • Difference between List form and InfoPath form? 2014-04-28

    Why and when we have to use InfoPath forms and when should we use List Forms? --------------Solutions------------- Info-Path forms are mostly designed and developed by SharePoint power user's and list forms are mostly developed by SharePoint Develope

  • Difference between List, List ? , List T , List E , and List Object 2011-06-03

    What are the differences between List, List<?>, List<T>, List<E>, and List<Object>? Now I do not blindly ask this question, so please don't close this thread. Let me first introduce the base code: private static List<String>

  • What is the difference between list controllers and set controllers? 2014-08-31

    What is the difference between list controllers and set controllers? --------------Solutions------------- The two controllers that are available to you are: StandardController StandardSetController StandardController From the docs: A Visualforce cont

  • What is the difference between green and red MAC addresses in wavemon's scan list? 2015-03-07

    In wavemon, what does red vs. green mean for the MAC addresses in the scan list? For example: The wavemon man page says: Scan window (F3) ... Each entry starts with the ESSID, followed by the colour-coded MAC address and the signal/channel informatio

  • Difference between list comprehension and generator comprehension with `yield` inside 2016-01-27

    What is the difference between list comprehensions and generator comprehensions with yield inside? Both return a generator object (listcomp and genexpr respectively), but upon full evaluation the latter adds what seem to be rather superfluous Nones.

  • The difference between List MyClass and MyClass[] 2016-02-04

    This question already has an answer here: Array versus List<T>: When to use which? 11 answers What is the difference between List<MyClass> and MyClass[] in C#. Thanks --------------Solutions------------- MyClass[] is an array, and once set in

  • How to validate a proxy in python? What's the difference between urllib2 and httplib? 2016-01-28

    i've been working on a web crawler using scrapy. When i tried to use a proxy to avoid being banned, i want to select several available proxies at first. And that's when i'm confused. At first,i was using following code: def validate_proxy_urllib2(sel

  • Difference between list assignment 2016-01-26

    This question already has an answer here: Multiple assignment and evaluation order in Python 5 answers Help me understand difference between list assignment. I have found that assignment like this a[0] = b[0] b[0] = a[0] Is different from a[0], b[0]

  • Difference between Wine and Mono 2011-03-21

    As far as I know, both Wine and Mono are used to run Windows applications under Ubuntu. So I was wondering what their differences are? Are they both virtual machines? Or does each belong to some other category? It is better When to use which for what

  • What is the difference between PATH and LD_LIBRARY_PATH? 2012-08-08

    I am having some difficulties understanding the difference between PATH and LD_LIBRARY_PATH. I have an installation setup that needs a file pkg.tcl and I am not where to add the path to it: should it be to PATH or LD_LIBRARY_PATH? --------------Solut

  • Why is there a difference between text and binary files in Windows? 2013-11-19

    In many different programming languages, there are constructs in place to specifically work around the fact that Windows differentiates between text and binary files. For example, in Ruby: f = File.open('filename.bin', 'rb') # read a file in binary m

  • What is the difference between Serializable and Externalizable in Java? 2009-05-03

    What is the difference between Serializable and Externalizable in Java? --------------Solutions------------- To add to the other answers, by implementating java.io.Serializable, you get "automatic" serialization capability for objects of your cl

  • Difference between wait() and sleep() 2009-06-24

    What is the difference between a wait() and sleep() in Threads? Is my understanding that a wait()-ing Thread is still in running mode and uses CPU cycles but a sleep()-ing does not consume any CPU cycles correct? Why do we have both wait() and sleep(

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development


Front-end development


development tools

Open Platform

Javascript development

.NET development

cloud computing


Copyright (C) avrocks.com, All Rights Reserved.

processed in 1.686 (s). 13 q(s)