 <p>For one thing, you're using content1 as the outer index in the first chunck of code, so matric should be initialized with content1 on the outer as well:</p> <pre><code>matrix = [[0 for x in range(len(content2))] for x in range(len(content1))] </code></pre> <p>And yes, you can do it in one line like the other answer mentions:</p> <pre><code>matrix = [[1 if i == j else 0 for j in content2] for i in content1] </code></pre>