Follow instructions

We've already seen examples of lists. Here, we'll look at how we can modify already existing lists.

Empty list

Here's how to create a variable as an empty list:

angles = []

We must include the square brackets to show that it is a list, but if nothing is written in between them it is an empty list. It's like a blank notebook that's just waiting to have something written in it.
Soon we will write something in the notebook- to add something to the list - we use append:

angles = []
angles.append(75)
angles.append(50)
angles.append(100)
print(angles)

Random list

Remember the random module? If we first create an empty list, we can then use random.randint to add random numbers to that list. If we do it in a list, we can get a list with as many random numbers as we want. But remember - we must create the list before the loop!

import random
angles = []
for i in range(0, 5):
    random_angle = random.randint(10, 300)
    angles.append(random_angle)
print (angles)

Later, we can use that list to describe how the turtle should turn after each move:

import turtle
turtle.color('black')
for angle in angles: 
    turtle.left(angle) 
    turtle.forward(75)

This is also a for loop! But instead of using range, or looping over a string, we loop over every number in the list angles. Because this is a new loop after the first one is done, there are angles in the list now.

Add both parts of code to one program and run it to see what happens.

Fill in the list

Instead of the randomization, we can ask the user what to add to the list:

angles = [] 

for i in range(0, 5): 
    angle = int(input("Next angle? ")) 
    angles.append(angle) 

print(angles)

We can do this with an infinite loop as well. Here's a complete example:

Here, the number 0 is used a "special command". If you enter 0, the if statement becomes true, and Python executes the instruction break which terminates the loop. In that case, the next loop takes over, and starts moving the turtle, once for each angle in the list angles.

Read page in other languages

In this video, we see an example of the usefulness of empty lists by temporarily storing instructions in it.

  • List: A list is a collection of data in order. Can also be known as "array" in other programming languages.
  • Variable: A part of the computer's memory where we can store something, like a piece of text, a name, or a number.
  • Funktion: Small, reusable parts of our code, for example input, print, sum, len, append, min or max. Sometimes referred to as methods.
  • range: Creates an interval that can be used in loops to repeat code, for example all numbers between 1 and 10.
  • Modul: We can reuse code that others have written in our programs. So that it doesn't become overwhelming, it is divided into modules, which we can import if necessary. A module contains one or more functions.
  • Loop: Another word for repetition in programming. In Python, we use the keywords while and for.
Difficulty level