What is the difference between using list[num] and len(list[num]) in a for loop?

256 Views Asked by At

As part of the project, I am supposed to build a memory game, which involves randomizing a list of 16 digits (two identical ranges of range(7)) and printing those digits onto a canvas. My first iteration had a for loop that picks each number of the list and prints it onto the canvas at a set interval (middle_cell_point) as such:

def draw(canvas):

    middle_counter = 1

    for num in full_list:

        canvas.draw_text(str(full_list[num]), (((middle_cell_point * middle_counter)) 
                          - (middle_cell_point/2) , HEIGHT/2), 22, "Red")
        middle_counter += 1  

the output from this repeats numbers on the canvas, but when I debug the code it seems to accurately assign numbers and does not seem to repeat any. The program works properly When I replaced "full_list" with "range(len(full_list))" in the for-loop:

def draw(canvas):

    middle_counter = 1

    for num in range(len(full_list)):

        canvas.draw_text(str(full_list[num]), (((middle_cell_point * middle_counter)) 
                              - (middle_cell_point/2) , HEIGHT/2), 22, "Red")
        middle_counter += 1  

could someone explain to me why the second iteration works and the first one does not?

Thanks a lot!

2

There are 2 best solutions below

2
Wolph On BEST ANSWER

The difference is that for num in full_list lists the items and for num in range(len(full_list)) lists the indices.

To illustrate:

>>> full_list = ['a', 'b', 'c']
>>> list(full_list)
['a', 'b', 'c']
>>> list(range(len(full_list)))
[0, 1, 2]

In your case you want to use num instead of full_list[num]:

def draw(canvas):

    middle_counter = 1

    for num in full_list:

        canvas.draw_text(str(num), (((middle_cell_point * middle_counter)) 
                                    - (middle_cell_point/2) , HEIGHT/2), 22, "Red")
        middle_counter += 1  
0
Gorka Sanz Monllor On

The first one iterates through the values of the initial vector si resulta are not correct. The second one iterates through the indexes if the vector from one to the Max length si valúes are correct