Python: Why a tuple operates faster than a list

Source: Internet
Author: User
Tags iterable

Dive into Python says that a tuple is an immutable list, and once a tuple is created, it cannot be changed in any way. But a Tuple operates faster than a list. If you define a constant set of values and the only thing you want to do with it is to iterate over it, use tuple instead of list.

I wrote a few lines of code to test it:

Example_list=list () for I in Range (0,500,1):    example_list.append (i) example_tuple=tuple (example_list) start= Time.clock () for item in Example_list: Does    somethingprint "iterate list:", Time.clock ()-startstart=time.clock () for Item in Example_tuple: Do   somethingprint "iterate tuple:", Time.clock ()-start

The results of the operation are as follows:

Iterate list:9.37050717647e-05
Iterate tuple:6.8270838e-05

I run it a few times, although the time will change, but traversing a tuple is really faster than a list. Why is it? StackOverflow on the other person's explanation:

Http://stackoverflow.com/questions/3340539/why-is-tuple-faster-than-list

There are a few key points to follow:

1, the tuple is immutable, in CPython the tuple is stored in a fixed contiguous memory, the creation of a tuple only need to allocate memory once. But the list is stored in two pieces of memory, a piece of memory fixed size, a Python object (a list objects) information, the other is a non-fixed size of memory, used to store data. Therefore, a tuple can be quickly positioned (an array in c) when searching, and a list must traverse (a list in C). In the compilation, because the tuple is immutable, the Python compiler stores it in its function or in the "Constant table" (constants table) of the module. At run time, just find these pre-built const tuples. But the list is mutable and must be built in the run, allocating memory.

3, when the elements of the tuple is a list, it only stores the list of references, (c in the fixed-length array of an element is a pointer to a linked list), the location of the search will be faster than the list

4. The CPython has been optimized to reduce memory allocation times: When a list object is released, its memory is saved in a free list for re-use. However, when a non-empty list is created, it still needs to be allocated memory storage data.

Tuple Source Code
Class tuple (object): "" "tuple (), empty tuple tuple (iterable), tuple initialized from iterable ' s items    If The argument is a tuple, the return value is the same object. "" "Def count (self, value): # Real signature unknown;     Restored from __doc__ "" "T.count (value)--return number of occurrences of value" "" Return 0 def index (self, value, Start=none, Stop=none): # Real signature unknown;        Restored from __doc__ "" "T.index (value, [Start, [Stop]), integer-return first index of value.        Raises valueerror if the value is not present. "" "Return 0 def __add__ (self, y): # Real signature unknown; Restored from __doc__ "" "x.__add__ (y) <==> x+y" "" Pass Def __contains__ (self, y): # real Signatur e unknown; Restored from __doc__ "" "X.__contains__ (y) <==> y in X" "" Pass Def __eq__ (self, y): # Real Signat Ure unknown;        Restored from __doc__"" "X.__eq__ (y) <==> x==y" "" Pass Def __getattribute__ (self, name): # real signature unknown;  Restored from __doc__ "" "x.__getattribute__ (' name ') <==> x.name" "" Pass Def __getitem__ (self, y): # Real Signature Unknown; Restored from __doc__ "" "x.__getitem__ (y) <==> x[y]" "" Pass Def __getnewargs__ (self, *args, **kwa RGS): # Real Signature Unknown pass def __getslice__ (self, I, j): # Real signature unknown;  Restored from __doc__ "" "X.__getslice__ (i, J) <==> X[i:j] use of        Negative indices is not supported. "" "Pass Def __ge__ (self, y): # Real signature unknown; Restored from __doc__ "" "x.__ge__ (y) <==> x>=y" "" Pass Def __gt__ (self, y): # Real Signature U Nknown; Restored from __doc__ "" "X.__gt__ (y) <==> x>y" "" Pass Def __hash__ (self): # real Signature UNK Nown;      Restored from __doc__  "" "x.__hash__ () <==> hash (x)" "" Pass Def __init__ (self, seq= ()): # Known special case of Tuple.__init_                _ "" "Tuple (), empty tuple tuple (iterable), tuple initialized from iterable ' s items        If The argument is a tuple, the return value is the same object. # (copied from class Doc) "" "Pass Def __iter__ (self): # real signature unknown; Restored from __doc__ "" "x.__iter__ () <==> iter (x)" "" Pass Def __len__ (self): # real Signature UN known; Restored from __doc__ "" "x.__len__ () <==> len (x)" "" Pass Def __le__ (self, y): # Real Signature UN known; Restored from __doc__ "" "x.__le__ (y) <==> x<=y" "" Pass Def __lt__ (self, y): # Real Signature U Nknown; Restored from __doc__ "" "X.__lt__ (y) <==> x<y" "" Pass Def __mul__ (self, n): # Real Signature U Nknown; Restored from __doc__ "" "X.__mul__ (n) <==> x*n "" "Pass @staticmethod # known case of __new__ def __new__ (S, *more): # Real signature unknown; Restored from __doc__ "" "t.__new__ (S, ...) A new object with type S, a subtype of T "" "Pass Def __ne__ (self, y): # Real signature unknown; Restored from __doc__ "" "x.__ne__ (y) <==> x!=y" "" Pass Def __repr__ (self): # real Signature Unkno Wn Restored from __doc__ "" "x.__repr__ () <==> repr (x)" "" Pass Def __rmul__ (self, n): # real Signatur e unknown; Restored from __doc__ "" "X.__rmul__ (n) <==> n*x" "" Pass Def __sizeof__ (self): # real Signature UN known; Restored from __doc__ "" "t.__sizeof__ ()--size of T in memory, in bytes" "" Pass
 list Source
Class List (object): "" "List (), New empty list List (iterable), new list initialized from Iterable ' ite MS "" "Def append (self, p_object): # Real signature unknown; Restored from __doc__ "" "L.append (object)--Append object to End" "" Pass Def count (self, value): # REA L signature Unknown;     Restored from __doc__ "" "L.count (value)--return number of occurrences of value" "" Return 0 def extend (self, iterable): # Real signature unknown;     Restored from __doc__ "" "L.extend (iterable) – Extend list by appending elements from the iterable" "" Pass def index (self, value, Start=none, Stop=none): # Real signature unknown;        Restored from __doc__ "" "L.index (value, [Start, [Stop]), integer-return first index of value.        Raises valueerror if the value is not present. "" "Return 0 def insert (self, Index, p_object): # Real signature unknown;     Restored from __doc__   "" "L.insert (Index, object)--Insert object before index" "Pass def pop (self, index=none): # real Signatur e unknown;        Restored from __doc__ "" "" "" L.pop ([index]), item-Remove and return item at index (default last).        Raises indexerror If list is an empty or index is out of range. "" "Pass def Remove (self, value): # Real signature unknown;        Restored from __doc__ "" "" L.remove (value)--Remove first occurrence of value.        Raises valueerror if the value is not present. "" "Pass Def Reverse (self): # real signature unknown; Restored from __doc__ "" "L.reverse () – Reverse *in place*" "" Pass def sort (self, cmp=none, Key=none, R Everse=false): # Real signature unknown;        Restored from __doc__ "" "L.sort (Cmp=none, Key=none, Reverse=false)--stable sort *in place*; CMP (x, y)-1, 0, 1 "" "Pass Def __add__ (self, y): # Real signature unknown; RestoredFrom __doc__ "" "x.__add__ (y) <==> x+y" "" Pass Def __contains__ (self, y): # Real Signature Unknown ; Restored from __doc__ "" "X.__contains__ (y) <==> y in X" "" Pass Def __delitem__ (self, y): # real S Ignature unknown; Restored from __doc__ "" "x.__delitem__ (y) <==> del x[y]" "" Pass Def __delslice__ (self, I, J): # r EAL signature Unknown; Restored from __doc__ "" "X.__delslice__ (i, J) <==> del X[i:j] Us        E of negative indices is not supported. "" "Pass Def __eq__ (self, y): # Real signature unknown; Restored from __doc__ "" "x.__eq__ (y) <==> x==y" "" Pass Def __getattribute__ (self, name): # real S Ignature unknown;  Restored from __doc__ "" "x.__getattribute__ (' name ') <==> x.name" "" Pass Def __getitem__ (self, y): # Real Signature Unknown; Restored from __doc__ "" "x.__getitem__ (y) <==> x[y]""Pass Def __getslice__ (self, I, j): # Real signature unknown;  Restored from __doc__ "" "X.__getslice__ (i, J) <==> X[i:j] use of        Negative indices is not supported. "" "Pass Def __ge__ (self, y): # Real signature unknown; Restored from __doc__ "" "x.__ge__ (y) <==> x>=y" "" Pass Def __gt__ (self, y): # Real Signature U Nknown; Restored from __doc__ "" "X.__gt__ (y) <==> x>y" "" Pass Def __iadd__ (self, y): # Real Signature Unknown Restored from __doc__ "" "x.__iadd__ (y) <==> x+=y" "" Pass Def __imul__ (self, y): # Real Signature Unknown Restored from __doc__ "" "X.__imul__ (y) <==> x*=y" "" Pass Def __init__ (self, seq= ()): # known Spec ial Case of list.__init__ "" "List (), New empty list List (iterable), new list initialized F      Rom iterable ' s items # (copied from class Doc)  "" "Pass Def __iter__ (self): # real signature unknown; Restored from __doc__ "" "x.__iter__ () <==> iter (x)" "" Pass Def __len__ (self): # real Signature UN known; Restored from __doc__ "" "x.__len__ () <==> len (x)" "" Pass Def __le__ (self, y): # Real Signature UN known; Restored from __doc__ "" "x.__le__ (y) <==> x<=y" "" Pass Def __lt__ (self, y): # Real Signature U Nknown; Restored from __doc__ "" "X.__lt__ (y) <==> x<y" "" Pass Def __mul__ (self, n): # Real Signature U Nknown; Restored from __doc__ "" "X.__mul__ (n) <==> x*n" "" Pass @staticmethod # known case of __new__ D EF __new__ (S, *more): # Real signature unknown; Restored from __doc__ "" "t.__new__ (S, ...) A new object with type S, a subtype of T "" "Pass Def __ne__ (self, y): # Real signature unknown; Restored from __doc__ "" "x.__ne__ (y) <==> x!=y" "" "Pass DEF __repr__ (self): # real signature unknown; Restored from __doc__ "" "x.__repr__ () <==> repr (x)" "" Pass Def __reversed__ (self): # real Signatu Re unknown; Restored from __doc__ "" "L.__reversed__ () – Return a reverse iterator over the list" "" Pass def __rmul __ (self, N): # real signature unknown; Restored from __doc__ "" "X.__rmul__ (n) <==> n*x" "" Pass Def __setitem__ (self, I, y): # Real Signa Ture unknown;  Restored from __doc__ "" "x.__setitem__ (i, y) <==> x[i]=y" "" Pass Def __setslice__ (self, I, J, y): # Real Signature Unknown; Restored from __doc__ "" "X.__setslice__ (i, J, y) <==> x[i:j]=y U        SE of negative indices is not supported. "" "Pass Def __sizeof__ (self): # real signature unknown; Restored from __doc__ "" "l.__sizeof__ ()--size of L in memory, in bytes" "" Pass __hash__ = None

The same usage for list and tuple:

>>> t = ("A", "B", "Mpilgrim", "Z", "example") >>> t (' A ', ' B ', ' Mpilgrim ', ' z ', ' example ') >>> t [0]                                       ' A ' >>> t[-1]                                      ' example ' >>> T[1:3]                                     (' B ', ' Mpilgrim ')

List and tuple definitions, indexes, shards (slice) in the same way

List and tuple different uses:

(1)

>>> T (' A ', ' B ', ' Mpilgrim ', ' z ', ' example ') >>> t.append ("new")    Traceback (innermost last):  File "<interactive input>", line 1, in? Attributeerror: ' Tuple ' object have no attribute ' append ' >>> t.remove ("z")      Traceback (innermost last):  File "<interactive input>", line 1, in? Attributeerror: ' Tuple ' object have no attribute ' remove ' >>> t.index ("Example") Traceback (innermost last):  File "<interactive input>", line 1, in? Attributeerror: ' Tuple ' object has no attribute ' index ' >>> ' z ' in T           True

From the source code can also be seen, the tuple does not have append\extend\remove\pop\index and other usages. However, you can use in to see if an element exists in a tuple .

(2)

d=dict () d[example_tuple]= "a" d[example_list]= "B" 

Traceback (most Recent:
  File "n:/workspace/python-workspace/tuple_test.py", line <module>
 & nbsp;  d[example_list]= "B"
typeerror:unhashable type: ' list '

Tuple2= ([2,3,4,5], [1,2,4,5])
d=Dict ()
d[tuple2]="a"

Traceback (most recent):
File "n:/workspace/python-workspace/tuple_test.py", line +, in <module>
D[tuple2]= "a"
Typeerror:unhashable type: ' List '

Tuples can be used as key in dictionary, but list is not. In fact, things are more complicated than that. The Dictionary key must be immutable. The tuple itself is immutable, but if you have a list of tuple, it is considered mutable, and it is unsafe to be used as a dictionary key. Only strings, integers, or other dictionary-safe tuples can be used as dictionary keys.

The tuple and list convert to each other:
Example_list=list () for I in Range (0,10,1):    example_list.append (i) example_tuple=tuple (example_list) Example_ List2=list (example_tuple) print "tuple", example_tupleprint "list", Example_list2

Operation Result:

Tuple (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The built-in tuple function receives a list and returns a tuple with the same element. The list function receives a tuple and returns a list.

Python: Why a tuple operates faster than a list

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.