Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a list independent of itself(?)

Tags:

python

list

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
like image 312
digital farmer Avatar asked Nov 23 '25 03:11

digital farmer


1 Answers

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))
like image 56
Elazar Avatar answered Nov 25 '25 17:11

Elazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!