Deutsch   English   

10. Lists and tupels

 

 

YOU LEARN HERE...

 

how to store multiple values in a list or tuple and access this data agai

 

 

EXAMPLES

 

Instead of storing values in different variables a, b, c individually, Python provides data types that can be used as containers for any number of data. In other programming languages, arrays are often used for this purpose. In contrast to arrays, lists do not have a fixed, predefined length, i.e. their length is automatically adapted to the number of stored elements (dynamic data structure).

The elements of a list are written in square brackets, e.g. a list of color names:

colors = [“red”, “blue, ‘green’]

The values of a tuple are written in round brackets, e.g. x, y coordinates of a point:

pt = (10, 20)

In contrast to lists, the values of tuples can no longer be changed after the program has been started. Lists and tuples can also be combined, e.g. a list with coordinates of corner points of a figure:

corners = [(2, 3), (5, 8), 7, 1)]]

Example 1: Accessing the elements of a list
You can iterate through the elements of a list using a for loop. In the example, the colors list consists of 7 color names.

With the for loop for c in colors: you go through the list in sequence and draw a filled circle with this color, which is displayed for 600 milliseconds. The loop commands must be indented.

You can also access the elements of a list with an index. The first element has the index 0, so corners[3] is not the third, but the fourth element, in the example the color “magenta”.

 

Program:      

# Gp10a.py
from gpanel import *

makeGPanel(-10, 10, -10, 10)
colors = ["red", "blue", "yellow", "magenta", "green", "cyan"]

for c in colors:
    setColor(c) 
    fillCircle(4)
    delay(600)
    
setColor(colors[3])
fillCircle(6)
► Copy to clipboard

 

Example 2: Drawing a polygon with the list of corner points
Use tuples for the coordinates of the corner points, e.g. (4, 2). All corner points are summarized in the list corners = [(4. 2), (1, 4) ...].

The fillPolygon(corners) function expects a list of point coordinates as a parameter and fills the enclosed area.

 

Program:     

# Gp10b.py
from gpanel import *

makeGPanel(0, 10, 0, 10)
corners = [(4, 2), (1, 4), (3, 7), (6, 8), (7, 5), (5, 3)]
setColor("blue")

for pt in corners:
    fillPolygon(corners)
► Copy to clipboard


Example 3: Creating the elements of a list with mouse clicks

The list is a dynamic data structure, i.e. you can also add the elements while the program is running.

In the example, you create an empty list with corners = [ ] and enter the number of corners of a polygon in an input dialog. You insert the points with mouse clicks. To do this, use the corners.append((x, y)), function, which adds the point with the coordinates (x, y) at the end of the list. len(corners) specifies the current number of elements in the list.

 

Program:      

# Gp10c.py
from gpanel import *

def onMousePressed(x, y):
    pos(x, y)
    circle(0.1)
    corners.append((x, y))
    if len(corners) == n:
        for pt in corners:
            fillPolygon(corners)
    
makeGPanel(0, 20, 0, 20, mousePressed = onMousePressed)
corners = []
n = inputInt("Gib Anzahl Ecken an")
setColor("magenta")
► Copy to clipboard

 

Example 4: Create points with mouse clicks and draw all connecting lines

In this example, it is advantageous to designate the points with p and q, whereby the points are given with a coordinate tuplel p = (x, y) After each mouse click, a small circle is drawn at point p, then p is connected to all existing points q in the corners list and added to the list.

 

Program:     

# Gp10d.py
from gpanel import *

def onMousePressed(x, y):
    p = (x, y)
    pos(p)
    fillCircle(0.2)
    for q in corners:
        line(p, q)
    corners.append(p)
  
corners = []
makeGPanel(0, 20, 0, 20, mousePressed = onMousePressed)
► Copy to clipboard

 

 

REMEMBER YOU...

 

You can store any amount of data under a name in a list and access this data with an index. Square brackets are used for the list notation. If you want to run through all elements of the list, the easiest way is to use a for loop for x in list: List is a dynamic data structure; elements can be added or removed during program execution.

Values of a tuple are written in round brackets. In contrast to the list, these cannot be changed after the program has started.

 

 

TO SOLVE BY YOURSELF

 

1)


Enter with an input dialog
z = inputInt(“Enter a number”)
8 numbers between 1 and 10 and save them in a list of numbers. Print the list in the output window using the print() function. You can sort the list with the sort() function.

Then output the list sorted by size with the print() command.

 


 

2)


Draw filled circles with the colors from the list
colors = [“red”, “blue”, “yellow”, “magenta”, “green”, “cyan”].

 


 

3)


Draw a house using a list with the coordinates of the corner points.

 


 

4)


Add to example 4 so that a set of points with connecting lines is created dynamically with the left mouse click and the closed areas in which the coordinates of the mouse click lie are colored with the right mouse click.

As in example 5 in the previous section, you must first check whether the left or right mouse button has been pressed.

def onMousePressed(x, y):
    if isLeftMouseButton():
        ....
        
    if isRightMouseButton():
       .....  
 


 

 

ADDITIONAL INFORMATION:

 

The most important operations with lists

 
 

li[i]

li.append(element)

li.insert(i, element)

li.index(element)

li.pop(i)

pop()

len(li)

del li[i]

li.reverse() 

li.sort() 

Access list element with index i

Append to the end

Insert at position i (element i moves to the right)

Searches for the first occurrence and returns its index

Removes the element with index i and returns it

Removes the last element and returns it

Returns the number of list elements

Removes the element with index i

Reverses the list (last element becomes the first)

Sorts the list (comparison with standard procedure)