I am experimenting with lists and was trying to get the following code segment to display:
----------
---hello--
----------
But to do this I need to get the 3 'listSmall's to be independent of one another. Is there a way to do this?
(
current output is of course:
---hello--
---hello--
---hello--
)
listSmall = ['-','-','-','-','-','-','-','-','-','-',]
listBig = [listSmall, listSmall, listSmall]
word = 'hello'
wordPosX = 3
wordPosY = 2
for i in word:
listBig[wordPosY][wordPosX] = i
wordPosX = wordPosX + 1
i = 0
while i != 3:
print ''.join(listBig[i])
i = i + 1
This is because list is mutable.
listBig = [listSmall, listSmall, listSmall]
makes listBig point three times to the same mutable list, so when you change this mutable list through on of these references, you will see this change through all the three.
You should make three distinct lists:
listBig = [ ['-'] * 10 for _ in range(3)]
no need for listSmall at all.
the whole code:
listBig = [ ['-'] * 10 for _ in range(3)]
word = 'hello'
wordPosX, wordPosY = 3, 1
listBig[wordPosY][3: (3+len(word))] = word
for v in listBig:
print(''.join(v))
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