184_notes:lists

Coding: Lists

We often need a way to represent a group of objects or values in code. Python makes this easy with lists. A list gives a name to a collection of any Python objects. You can think of a list like an excel spreadsheet, it has many rows (each representing an object), and each row has several columns (representing the attributes of the object).

In Glowscript, we often use lists that include spheres, arrows, rings, and other shapes. Creating a list is easy:

 
list_of_numbers = [1, 1, 3, 5, 8, 11]

point1 = point()
point2 = point()
point3 = point()

list_of_points = [point1, point2, point3]

You can also access each bucket in a list to update or retrieve the object within it. One way is by using list indexing. Indices in a Python list start at 0 for the first element:

list_of_numbers = [1, 1, 3, 5, 8, 11]
first_number = list_of_numbers[0]      # Read the first element, first_number now holds the value 1

To change the value in a bucket, simply use “=” to assign to it:

list_of_numbers[0] = 250               # Change the first element
first_number = list_of_numbers[0]      # first_number now holds the value 250

We often want to move through a list and read or change each value one-by-one. The easiest way to iterate through a list in Python is using a for loop.

list_of_numbers = [1, 1, 2, 3, 5, 8, 11]

for number in list_of_numbers:  # For loop
    print(number)

This works great for reading each element in a list. In the above code, “number” is a temporary variable. On each iteration of the for loop, number is assigned to the next element in the list “list_of_numbers” until none are left. Within the for loop, you can use the variable “number” to access the current element in the list. The above loop does not work for changing values in the list. To change values, we need to use a different kind of loop. Usually, the best choice is to use a while loop as below:

 
list_of_numbers = [1, 1, 2, 3, 5, 8, 11]
index = 0

while index < len(list_of_numbers):  # Conditional
    list_of_numbers[index] += 5      # Increase each number by 5
    index += 1                       # Increment the counter variable
  • 184_notes/lists.txt
  • Last modified: 2022/05/07 01:20
  • by woodsna1