Lists and Arrays
From GeoMod
Introduction
Lists and arrays hold a series of items in an ordered list. A vector is an example of an array, for example
from visual import * ball = sphere() ball.pos = vector(1,2,0)
creates a ball and moves it to the position x=1, y=2 and z=0. The vector is an array of three numbers.
Creating a list
Say we wanted to create a row of 5 spheres aligned along the x-axis, there are a number of ways to do it. One would be to create 5 spheres with different names with
from visual import * ball1 = sphere(pos=(0,0,0)) ball2 = sphere(pos=(2,0,0)) ball3 = sphere(pos=(2,0,0)) ball4 = sphere(pos=(2,0,0)) ball5 = sphere(pos=(2,0,0)) ball4.color = color.red
Another way to get the same thing is with a list, and we could define it like this
from visual import * balls=[] balls.append(sphere(pos=(0,0,0))) balls.append(sphere(pos=(2,0,0))) balls.append(sphere(pos=(4,0,0))) balls.append(sphere(pos=(6,0,0))) balls.append(sphere(pos=(8,0,0))) balls[3].color = color.red
This creates a list called "balls" with the statement
balls=[]
and adds 5 balls to the list by calling the list and using the append function. To change the color of the fourth ball we use the line
balls[3].color = color.red
The index for the 4th ball is 3 because the first item in a list is given the index of 0.
Lists and loops
Why make things complicated by using a list? Because we can, and with a list you can create the five balls using a loop. This becomes important when creating a large number of objects. To create the 5 balls with a loop and a list you can use.
from visual import *
balls=[]
for i in range(5):
balls.append(sphere(pos=(i*2,0,0)))
balls[3].color = color.red
The range loop for i in range(5): sets the value of i to 0, 1, 2, 3 and 4 consecutively, then the statement pos=(i*2,0,0) sets the position of the balls to be 0, 2, 4, 6 and 8 respectively.
Thus to change the number of balls we just need to change the value in the "range()" function.


