0

I am stuck on a list and do not get it - why do I get the result below:


    TenLast = [["."] * 10 ] * NumberOfHosts
    
    for i in range(0,NumberOfHosts):
        TenLast[i][0] = i
        
    print(TenLast)
    exit()
    [[6, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.']]

I would expect

    [[0, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [1, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [2, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [3, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [4, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [5, '.', '.', '.', '.', '.', '.', '.', '.', '.'], 
    [6, '.', '.', '.', '.', '.', '.', '.', '.', '.']]

thank you for for help,support and any ideas.

regards, HEP

MattDMo
  • 100,794
  • 21
  • 241
  • 231
HEP
  • 1
  • 1
  • 1
    Your sublists are all referring to the same list in memory. [Check this](https://stackoverflow.com/questions/2739552/2d-list-has-weird-behavor-when-trying-to-modify-a-single-value) – kcsquared Sep 01 '21 at 18:02

1 Answers1

2

Your sublists are all referring to the same list in memory. You can get around this by using itertools.

import itertools
TenLast = list(itertools.repeat([["."] * 10 ],NumberOfHosts))
for i in range(0,NumberOfHosts):
    TenLast[i][0] = i
print(TenLast)
Saurabh
  • 49
  • 2