listen
Deutsch   English   

12. LIST AND TUPLE

 

 

YOU LEARN HERE...

 

how you can store any number of values in a list or tuple and how to access these values.


 

WHY DO YOU NEED LISTS?

 

Instead of storing several values in different variables a, b, c individually, you can use lists or tuples. The values (elements) of a list are enumerated in square brackets, in a tuple in round brackets. For example:

List of colors:
colors = ["red", "blue", "yellow", "green"]

List with numbers
nb = [4, 2, 6, 3, 7]

Tuple with x, y coordinates of a point p:
p = (10, 20)

You access the individual values with an index. The first element always has index 0, the second index 1 and so on. For example, colors[2] returns the color “yellow” or p[0] the number 10. The difference between lists and tuples is that lists can be changed during program execution, whereas tuples cannot.

 

 

EXAMPLES

 

Example 1: Go through a list with a for loop
The Turtle is to draw filled circles in the colors red, blue, yellow and green.

You save the colors in the colors list and use a for-Schleife to select the colors in sequence.

There are two ways to do this.

 

You go through the list with an index i. The first element of the list has index 0. If n is the number of list elements (also known as the length of the list), the index i must run from 0 to n-1. You can determine the length n of the list with the built-in function n = len(colors).

Program:    

from gturtle import *

colors = ["red", "blue", "yellow", "green"]
n = len(colors)

for i in range(n):
    c = colors[i]
    setPenColor(c)
    dot(40)
    forward(40)
► Copy to clipboard

There is a second, shorter way of running through the list with a for-loop, where you do not need an index. With the notation

for c in colors:

you can fetch one element after the other from the colors list.

Program:    

from gturtle import *

colors = ["red", "blue", "yellow", "green"]

for c in colors:
    setPenColor(c)
    dot(40)
    forward(40)
► Copy to clipboard


Example 2: Tuples as elements of a list

Starting from the bottom left corner, draw a house by going through a list house with the coordinates of the corner points and connecting them in sequence with the moveTo(x, y) vcommand.

 

 

 

Program:    

from gturtle import*

house = [(0, 60), (50, 110), (100, 60), (100, 0), (0, 0)]
for (x, y) in house:
    moveTo(x, y)
► Copy to clipboard


Example 3: A dynamic list of points

So far you have defined the lists in the program code. However, you can also create a list at runtime during program execution (also known as “dynamically”).

In your program, you create a new point (x, y) with a mouse click and draw all connecting lines from this point to the existing points. To do this, you must save the existing points in a points list.

First create an empty list with points = [] . This draws a point at the location of the mouse click and adds the coordinates of the mouse click to the points list. To add the point to the list, write points.append((x, y)).

With each new point, the function drawLines(x, y) s called, which draws the connecting lines. Use a for loop to go through the list of existing points and connect each element with the newly created point.

 

Program:

from gturtle import *

def drawLines(x, y):
    for (x1, y1) in points:
        setPos(x, y)            
        moveTo(x1, y1)

def addPoint(x, y):
    setPos(x, y)    
    dot(8)    
    drawLines(x, y)
    points.append((x, y))        

makeTurtle(mousePressed = addPoint)
hideTurtle()
setPenColor("blue")
points = []
print("Click with the mouse to draw points!")
► Copy to clipboard


Example 4: Colored line graphics

Beautiful graphics can be created with the help of color lists.

The color is changed after each stroke, whereby after the last color of the list, the list is run through again from the beginning. Experiment with different colors and also change the number of colors.

The background is colored black with thel clear("black" command.

 

Program:    

from gturtle import *

clear("black")
colors = ["green", "yellow","red", "blue", "magenta"]
a = 5
while a < 300:
    for c in colors: 
        setPenColor(c) 
        forward(a)
        right(70)
        a = a + 0.8 
► Copy to clipboard

 

 

REMEMBER...

 

You can store several values in a list and access the individual elements via an index. When enumerating the list elements, use the square brackets.

Use li.append(x) to add a new element x to the end of the list li.
With for n in li: you go through the list li element by element.
A list can also be created or modified dynamically during program execution.

In addition to lists, Python also provides tuples for storing multiple values. The elements of a tuple are specified in the round brackets. Tuples are often used to save coordinates.

 

 

TO SOLVE BY YOURSELF

 
1.

Create a list of colors with 6 freely selected colors
(trinket.io/docs/colors). Draw a hexagon with one color from your colors list for each side color. Choose a wider pen for drawing the hexagon sides.

 
2.

Using random numbers, you can randomly select a color from the colors list:

from random import randint

colors = ["red", "blue", "yellow", "lime", "magenta"]
i = randint(0, 4)
c = colors[i]
print(c)


Write a program so that a circle is drawn at the mouse position each time the mouse is clicked, whereby the color is selected at random from the colors list.

As in example 3, define a callback function drawDot() that is called each time the mouse is clicked. In this function, the color is set randomly, the turtle is placed at the position of the mouse click and a dot is drawn.



 


3.

With each mouse click, a new circle is drawn and at the same time all existing circles are colored with the same color randomly selected from the colors list.

Use example 3 as a template. The addPoint(x, y) function is called each time the mouse is clicked. A new point (x, y) is added to the points list, which is empty at the beginning, and then the drawDot() function is called.

 

In the drawDot() function, you select a color and go through the points list to recolor all points.