[Tutor] matx3.py
Mats Wichmann
mats at wichmann.us
Wed Dec 27 23:01:42 EST 2023
On 12/27/23 15:34, Ethan Rosenberg wrote:
> Tutor -
> mat = [[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]]
> I receive an error that mat[k] = i*j is a tuple??
believe it or not your initialization of mat sets it to a tuple - a
tuple consisting of three lists, each consisting of three lists
containing a single element. The interactive interpreter will try to
show it as a tuple by adding parens, but it's not the parens that make
it a tuple: comma-separated elements that aren't otherwise enclosed in
known container syntax (e.g. list, set, dict) makes it a tuple.
>>> mat = [[1],[2],[3]],[[4],[5],[6]],[[7],[8],[9]]
>>> type(mat)
<class 'tuple'>
>>> mat
([[1], [2], [3]], [[4], [5], [6]], [[7], [8], [9]])
>>>
It's doubtful this is what you want. Nor your later code where you nest
loops three deep and will end up repeating stuff you don't expect. A
print statement here will show you what's happening:
....
for k in range(0,8):
print(f"Setting mat[{k}] to {i * j}")
mat[k] = i*j
Giving:
Setting mat[0] to 0
Setting mat[1] to 0
Setting mat[2] to 0
Setting mat[3] to 0
Setting mat[4] to 0
Setting mat[5] to 0
Setting mat[6] to 0
Setting mat[7] to 0
Setting mat[0] to 0
Setting mat[1] to 0
Setting mat[2] to 0
Setting mat[3] to 0
Setting mat[4] to 0
Setting mat[5] to 0
Setting mat[6] to 0
Setting mat[7] to 0
Setting mat[0] to 0
Setting mat[1] to 0
Setting mat[2] to 0
Setting mat[3] to 0
Setting mat[4] to 0
Setting mat[5] to 0
Setting mat[6] to 0
Setting mat[7] to 0
Setting mat[0] to 1
Setting mat[1] to 1
Setting mat[2] to 1
Setting mat[3] to 1
Setting mat[4] to 1
Setting mat[5] to 1
Setting mat[6] to 1
Setting mat[7] to 1
Notice the repeat setting of mat[0] through mat[7] (and no mat[8]), to
the wrong values, and think for a while until you understand why it's
working this way.
As I expect people have pointed out to you (sorry haven't followed the
whole thread), Python itself has no concept of a two-dimensional matrix.
If you want that, use the (external, and very popular) numpy module.
You can fake it with a list (single-dimensional array), as you're trying
to do.
If I've twigged what you want, something like this can set it up, trying
to avoid zero values - again, it's kind of a guess that this is what
you're after:
mat = []
for i in range(1, 4):
for j in range(1, 4):
mat.append(i * j)
You can write that whole thing as a "list comprehension", which is a bit
more advanced:
mat = [i * j for i in range(1, 4) for j in range(1, 4)]
And to print it out so it "looks" like a matrix you can get a little tricky:
for idx, elem in enumerate(mat, start=1):
print(elem, end=" " if idx % 3 else "\n")
That causes each third element to emit a line break after it's printed,
the other two will emit a space. The print function syntax shown is
slightly advanced, don't worry if you haven't seen that yet, you can
come back to that later.
More information about the Tutor
mailing list