[Tutor] lists, tuples, arrays

Bob Gailer ramrom@earthling.net
Mon Feb 24 21:19:01 2003


--=======77DE4F87=======
Content-Type: text/plain; x-avg-checked=avg-ok-267B1AE6; charset=us-ascii; format=flowed
Content-Transfer-Encoding: 8bit

At 04:37 PM 2/24/2003 -0500, John Keck wrote:

>I'm a somewhat experienced programmer (though not necessarily with 
>object-oriented code), but I'm having trouble understanding the 
>differences between using lists, tuples, and arrays, and maybe vectors.
>
>First of all, what are the basic differences between these different types?

Lists and tuples are sequences native to Python. Each element of these can 
be any Python object. Arrays are provided by certain modules. All elements 
of an array are the same type.

Lists and arrays are "mutable" meaning that elements can be changed, 
deleted, inserted. Tuples are immutable. There are a few cases where tuples 
are required.

>For example, I'm trying to set all the values of a slice of a list (or 
>array) to a particular value.

list = [1,2,4,3,5,8,7,9]
list[2:5] = [6]*3 # yields [1, 2, 6, 6, 6, 8, 7, 9]

>Another example: I'm have a list (or array) of vectors.  How do I multiply 
>all of them by a scalar?

In general you write a loop or use list comprehension. list = [i * 
scalarvalue for i in list]  will give you a new list with each element 
multiplied by the scalar. If you have a nested list [[1,2,3],[4,5,6]] then 
you must nest the loop.

>Another question: what is the difference between range() and arange()?

What is arange? Where did you see it? Are you thinking of xrange?

range creates a list. xrange acts as a iterator; giving one value after 
another rather than returning the entire list.
for i in range(5): is the same as
x = range(5)
for i in x:

whereas in
for i in xrange(5):
each time the loop cycles xrange delivers 0, then 1, up to 4, then raises 
an error which terminates the loop.

For a large range, range creates a large intermediate list, whereas xrange 
takes a little more work and avoids the memory impact of a large list.

Bob Gailer
mailto:ramrom@earthling.net
303 442 2625

--=======77DE4F87=======
Content-Type: text/plain; charset=us-ascii; x-avg=cert; x-avg-checked=avg-ok-267B1AE6
Content-Disposition: inline


---
Outgoing mail is certified Virus Free.
Checked by AVG anti-virus system (http://www.grisoft.com).
Version: 6.0.454 / Virus Database: 253 - Release Date: 2/10/2003

--=======77DE4F87=======--