Looping through a list

Here we show two ways to iterate over items in a list, this is very similar to string:

1, loop through each item in the list, use for... in ...

Loop through each number in the list, and build columns with height of the number, n means the index of each element.

lst = [3,5,8,9]
n = 0
for num in lst:
    print(num)
    column(n, num, -20, 42) 
    n += 1

Console results:

3
5
8
9

2, use list index number to loop through a list

Let's continue, loop through the list again, this time use list index, put columns at x=i (index number) with height = lst[i]

for i in range(len(lst)):
    column( i, -18, lst[i], 44)

See the game world structures: the back row (42: gray) is the first loop, the front row (44: light blue) is the second loop. Both ways work the same to loop through the list. We'll use list index to loop through list more often.

==more?

Demo list basics in CodeCraft

Since we know how to loop through a list, we can build structures in CodeCraft to demo some list basics such as list indexing, slicing, changing item's value.

First, build white columns representing the original number list:

# Original list
lst = [1,2,3,4,5,6,7,8,9]
for i in range(len(lst)):
    column( i, -20, lst[i], 35)   # white

Demo 1: access items at index number 2 and 4, highlight them blue and yellow

column(2, -20, lst[2], 62)     # blue 
column(4, -20, lst[4], 76)   # yellow

Demo 2: change item's value using index

lst[7] = 5
column(7, -20, lst[7], 72)    # purple

The item at index 7 is assigned a new value, so the new column(purple, height:5) is shorter than the original column(red, height:8)

Keep the original list, comment out the demo 1 and 2, refresh the screen, try the following operations:

Demo 3: slicing list

lst_1 = lst[3:8]
for i in range(len(lst_1)):
    column(i+3, -20, lst_1[i], 2)   # cobblestone columns represent lst_1, [4,5,6,7,8]

# shift the original list to the front, z: -10
lst = [1,2,3,4,5,6,7,8,9]
for i in range(len(lst)):
    column( i, -10, lst[i], 35)    
 n
# another list slice
lst_2 = lst[1:8:2]
for i in range(len(lst_2)):
    column(2*i+1, -10, lst_2[i], 1) # brick columns represent lst_2 [2,4,6,8]

To make sure each picked out column in the slice has the same x location as the original list, for list slice lst[a:b:s], pay attention to the x value in column(), , each item has x value as s*i+a

results matching ""

    No results matching ""