Can anyone explain why this code is coded this way?

I am going through the week 3 lab 1 vector operation python notebook. and I am super confused about the plot vector function.

def plot_vectors(list_v, list_label, list_color):
    _, ax = plt.subplots(figsize=(10, 10))
    ax.tick_params(axis='x', labelsize=14)
    ax.tick_params(axis='y', labelsize=14)
    ax.set_xticks(np.arange(-10, 10))
    ax.set_yticks(np.arange(-10, 10))
    plt.axis([-10, 10, -10, 10])
    for i, v in enumerate(list_v):
        sgn = 0.4 * np.array([[1] if i==0 else [i] for i in np.sign(v)])
        plt.quiver(v[0], v[1], color=list_color[i], angles='xy', scale_units='xy', scale=1)
        ax.text(v[0]-0.2+sgn[0], v[1]-0.2+sgn[1], list_label[i], fontsize=14, color=list_color[i])


The part confuses me is the loop. I do not understand how it works since in the later data, there are three vectors containing the vector themselves, formatting and the colour, but in the loop there are only two variable i and v. how does this piece of code work?

Thank you in advance.

I recommend you look up the enumerate() function in the python documentation.

It returns a sequence of tuples - the first element is an index into the list. That is the ‘i’ value. The second element is a member of the list, that’s the ‘v’ value.

1 Like

The key point to understand is that i and v in the loop refer to the index and the vector, respectively. The corresponding label and color for each vector are accessed using this index i from list_label and list_color . So, even though the loop iterates over list_v , it uses the index i to access the corresponding elements in list_label and list_color

I hope this helps!

1 Like