Random Numbers, Tuples, and Lists

Lists

Lists are data structures used for storing an ordered list of items, where the position of each element is guaranteed to be fixed until the list is modified. Unlike tuples, lists can be modified after they are initialized. A pair of square brackets are used for initializing the lists.

import turtle
colors = ['red', 'purple', 'blue', 'green', 'orange', 'yellow']

turtle.bgcolor('black')
turtle.speed(20)

for x in range(360):
    turtle.pencolor(colors[x % 6])
    turtle.width(x / 100 + 1)
    turtle.forward(x)
    turtle.left(59)

turtle.done()

(Note: The original source of the code sample is unknown, however you can find a reference url to this example in www.geeksforgeeks.org/draw-colorful-spiral-web-using-turtle-graphics-in-python/)

How can we populate a list from the values returned by the range() function?

Using the star /asterisk * operator as in the following to unpack the range result:

my_list = [*range(20)]

print(my_list)

my_second_list = [*range(10,50,3)]

print(my_second_list)



Another alternative is to use list comprehension with a generator expression:

my_list = [2*x for x in range(10,50,2) ]
print(my_list)

which will retrieve a collection of numbers using the range function and assign twice as much as each x value to the list in the order they are iterated by the for statement. Note that this use of for does not have a body or colon (:).


The following example appends multiples of 5 to the list from the range(100):

my_list = [x for x in range(101) if x % 5 == 0 ]
print(my_list)

Receiving a string containing coordinates separated by commas :

coordinates = [int(c) for c in input().split(',') ]
print(coordinates)

The generator expression does not work with tuples in means of comprehension, you can use tuple() constructor instead:

my_tuple = tuple(x for x in range(101) if x % 5 == 0 )

If you need to add items to a list after a more complicated processing, you can use the append function as in

my_list = []

for x in range (20):
    if(x%2 == 0):
        my_list.append(x)

print(my_list)

which will output [0, 2, 4, 6, 8, 10, 12, 14, 16, 18] .