By coolios


2019-12-02 22:13:59 8 Comments

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

2 comments

@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!

@xiaofeng.li 2019-12-02 22:25:20

Like this answer.

@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.

Related Questions

Sponsored Content

46 Answered Questions

[SOLVED] How to make a flat list out of list of lists?

23 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

16 Answered Questions

[SOLVED] What are metaclasses in Python?

24 Answered Questions

[SOLVED] Limiting floats to two decimal points

63 Answered Questions

[SOLVED] Calling an external command from Python

28 Answered Questions

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

  • 2008-09-10 06:20:11
  • Ray Vega
  • 2559431 View
  • 3235 Score
  • 28 Answer
  • Tags:   python list

29 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3542635 View
  • 2905 Score
  • 29 Answer
  • Tags:   python list indexing

21 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3779321 View
  • 3474 Score
  • 21 Answer
  • Tags:   python directory

18 Answered Questions

[SOLVED] Convert bytes to a string

19 Answered Questions

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

  • 2009-02-06 22:47:54
  • Joan Venge
  • 1950852 View
  • 3332 Score
  • 19 Answer
  • Tags:   python loops list

Sponsored Content