#### [SOLVED] Python concept regarding lists and loops

By coolios

I am lost as to why this function works the way it does.

``````a = [[0, 1, 2],
[2, 3, 4],
[4, 5, 6]]
for i in range(len(a)):
for j in range(len(a)):
if i == j:
print(a[i][j])
``````

The output for this function is:

``````0
3
6
``````

#### @Mark Reed 2019-12-02 22:21:12

It loops `i` from 0 to 2. For each `i`, it loops `j` from 0 to 2, too. Then it compares them and only prints out the item at `a[i][j]` if `i` and `j` are the same value. So the loops go like this:

``````i=0; j=0. Does i==j? Yes. Print a[0][0], which is 0.
i=0; j=1. Does i==j? No.  Do not print anything.
i=0; j=2. Does i==j? No.  Do not print anything.
i=1; j=0. Does i==j? No.  Do not print anything.
i=1; j=1. Does i==j? Yes. Print a[1][1], which is 3.
i=1; j=2. Does i==j? No.  Do not print anything.
i=2; j=0. Does i==j? No.  Do not print anything.
i=2; j=1. Does i==j? No.  Do not print anything.
i=2; j=2. Does i==j? Yes. Print a[2][2], which is 6.
``````

It's basically a really long-winded way of writing this.

``````for i in range(len(a)):
print(a[i][i])
``````

#### @coolios 2019-12-02 22:22:51

Oh, I see it now! thank you so so so much this really really helped!

#### @kaya3 2019-12-02 22:16:26

Since the print statement only happens when `i == j`, we can simplify this code to just a single loop:

``````for i in range(len(a)):
print(a[i][i])
``````

Then it's clear what's happening: it prints the elements from the diagonal, where the x and y coordinates are the same.

### [SOLVED] How do I check if a list is empty?

• 2008-09-10 06:20:11
• Ray
• 2858922 View
• 3234 Score
• Tags:   python list

### [SOLVED] Accessing the index in 'for' loops?

• 2009-02-06 22:47:54
• Joan Venge
• 2116324 View
• 3605 Score
• Tags:   python loops list

### [SOLVED] Finding the index of an item in a list

• 2008-10-07 01:39:38
• Eugene M
• 3879415 View
• 3181 Score
• Tags:   python list indexing