Lists and Tuples

Robert Brewer fumanchu at amor.org
Fri Dec 5 01:23:24 EST 2003


Speed is a factor:

>>> timeit.Timer("a = (1, 2, 3)").timeit()
0.36679466245011483

>>> timeit.Timer("a = [1, 2, 3]").timeit()
0.82959342598011432

Building the 3-element list takes over twice as long as the 3-element
tuple. Extraction is also faster with tuples:

>>> timeit.Timer("""a = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
... b = a[1]""").timeit()
0.75013975239869524

>>> timeit.Timer("""a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
... b = a[1]""").timeit()
1.2107122553285308


Oh, and in case you're wondering, timeit() runs each statement 1,000,000
times unless you specify otherwise.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org

> -----Original Message-----
> From: Jeff Wagner [mailto:JWagner at hotmail.com] 
> Sent: Thursday, December 04, 2003 9:55 PM
> To: python-list at python.org
> Subject: Re: Lists and Tuples
> 
> 
> On 04 Dec 2003 21:31:12 -0800, Paul Rubin 
> <http://phr.cx@NOSPAM.invalid> wrotf:
> 
> >Jeff Wagner <JWagner at hotmail.com> writes:
> >> I've spent most of the day playing around with lists and tuples to
> >> get a really good grasp on what you can do with them. I am still
> >> left with a question and that is, when should you choose a 
> list or a
> >> tuple? I understand that a tuple is immutable and a list is mutable
> >> but there has to be more to it than just that.  Everything I tried
> >> with a list worked the same with a tuple. So, what's the difference
> >> and why choose one over the other?
> >        
> >
> >Try this with a list:
> >
> >  a = [1, 2, 3, 4, 5]
> >  a[3] = 27
> >  print a
> >
> >Then try it with a tuple.
> 
> That's because a tuple is immutable and a list is mutable but 
> what else? I guess I said everything I
> tried with a tuple worked with a list ... not mentioning I 
> didn't try to break the immutable/mutable
> rule I was aware of. Besides trying to change a tuple, I 
> could cut it, slice and dice it just like I
> could a list. They seemed to have the same built-in methods, too.
> 
> >From what I can see, there is no reason for me to ever want 
> to use a tuple and I think there is
> something I am missing. Why would Guido go to all the effort 
> to include tuples if (as it appears)
> lists are just as good but more powerful ... you can change 
> the contents of a list.
> 
> Jeff
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 





More information about the Python-list mailing list