Question

using python 3.4

ranks = [[0 for y in range(0,len(graph))] for x in range(0,iterSites)]
for site in ranks[0]:
    site = 2
print(ranks)

Output:

[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

Why does "site = 2" not set every value of ranks[0] to 2?

Was it helpful?

Solution

Because site is a copy of ranks[0][x] not the real value . What you have to do is something like:

for site in range(len(ranks[0])):
    ranks[0][site] = 2
print(ranks)

OTHER TIPS

site is a local variable, whose value will not be assigned to the value of the list. Change the code as shown below:

ranks = [[0 for y in range(0,len(graph))] for x in range(0,iterSites)]
for site in range(len(ranks[0])):
    ranks[0][site] = 2
print(ranks)

first of all you are doing site = 2 while you need to update rank

second ranks[0] is a list not a cell inside a list, so your iteration is not right.

You can change you code as follows:

ranks = [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]

for idx, value in enumerate(ranks[0][:]):
    ranks[0][idx] = 2

print ranks

Output:

[[2, 2, 2, 2, 2, 2, 2], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top