I want to set value of G[1][0],G[1][1]...G[1][100]
and G[0][1],G[1][1]...G[100][1]
to be 1
G = [[0]*101]*101
G[1][:] = 1
G[:][1] = 1
Than I got error,
...
G[1][:] = 1
TypeError: can only assign an iterable
how can I do this without Numpy?
There are a few flaws here.
First of all, the left-hand side of your assignment yields an iterable, so you can't assign a scalar to that. Instead, the right-hand side (in your case 1
) needs to be an iterable of equal length, e.g.:
G[0][:] = [0] * 101 # Warning: Copied code from question, still flawed
You initialize your list in-line. This is okay for a list of literals, but will fail for the second dimension, as it will hold 101 references to the same internal list. Changing one element in there will have effects on all other indices.
You want to initialize your list like this:
G = [[0] * 101 for x in range(102)]
The next thing is, that the [:]
-call creates a hard-copy of your list. So what happens here, is:
G[0][:]
takes the first column of your 2d list and hard-copies it.G[:][0]
hard-copies the entire 2d list and then returns the first column of that.You probably do not want to copy the entire list around all the time, losing its reference and making changes only to the copies.
Assuming your first dimension refers to columns and your second dimension refers to rows:
Set all elements of a column to 1
:
G[0] = [1] * 101
Set all elements of a row to 1
:
for i in range(102): G[i][0] = 1
First of all the way you created the list
is wrong
See this question and answer
Using loop:
import pprint
lst = [[0]*10 for n in range(10)]
for i in range(len(lst[0][:])): #Iterating over column of first row
lst[0][i] = 1
for j in range(len(lst)): #Iterating over row of first column
lst[j][0] =1
pprint.pprint(lst)
Output:
[[1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0]]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With