1

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?

Pius Friesch
  • 351
  • 1
  • 6
  • 14

3 Answers3

1

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)
anirudh
  • 4,116
  • 2
  • 20
  • 35
1

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)
billpcs
  • 633
  • 10
  • 17
0

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]]
Kobi K
  • 7,743
  • 6
  • 42
  • 86