-1

I am wondering why my for loop is not updating the old_hosts values and why is updating the workers in the following code? I am NOT assigning any new value to the workers variable!!!

workers = [['w1', 1],['w2',2]]
old_hosts = [['w1',-1],['w1',-11]]

for old_host in old_hosts:
    old_host = [*(worker for worker in workers if worker[0]==old_host[0])][0]
    old_host[1]= 3
    print('old_host: ' + str(old_host))
print('workers: ' + str(workers))
print('old_hosts: ' + str(old_hosts))

output:

old_host: ['w1', 1]
old_host: ['w1', 1]
workers: [['w1', 3], ['w2', 2]]
old_hosts: [['w1', -1], ['w1', -11]]

3 Answers3

3

because in for-loop you create a local variable and assign your array to a local variable and you don't change your old_hots at all.

For changing your array you need index and assign what you want to this index. for this purpose I use enumerate like below:

workers = [['w1', 1],['w2',2]]
old_hosts = [['w1',-1],['w1',-11]]

for idx , old_host in enumerate(old_hosts):
    old_hosts[idx] = [*(worker for worker in workers if worker[0]==old_host[0])][0]
print('workers: ' + str(workers))
print('old_hosts: ' + str(old_hosts))

Output:

workers: [['w1', 1], ['w2', 2]]
old_hosts: [['w1', 1], ['w1', 1]]
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • thank you, just I edited the question and am asking why the workers value is changed? – Mohammad Sadegh Aslanpour Sep 05 '21 at 10:59
  • @MohammadSadeghAslanpour welcome. this question is closing by other. maybe this is better ask another question. if this is correct please read this link : https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – I'mahdi Sep 05 '21 at 11:01
1

Your code was nearly correct. You have to assign to the list element you want to change not the variable. Your solution will break if old_hosts contains a worker id that is not in workers. I removed the redundant generator expression.

workers = [['w1', 1],['w2',2]]
old_hosts = [['w1',-1],['w1',-11]]

for old_host in old_hosts:
    old_host[1] = [worker[1] for worker in workers if worker[0]==old_host[0]][0]
    print('old_host: ' + str(old_host))
print('workers: ' + str(workers))
print('old_hosts: ' + str(old_hosts))

Output

old_host: ['w1', 1]
old_host: ['w1', 1]
workers: [['w1', 1], ['w2', 2]]
old_hosts: [['w1', 1], ['w1', 1]]
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
1
print('old_hosts: ' + str(old_hosts))

check this last line, change to

print('old_hosts: ' + str(old_host))
Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
Yasmin
  • 21
  • 2