Hjouji Anas - 1 year ago 49

Python Question

I seem to have a problem with my list generating script. I'm trying to convert a string into a list of string-lists, in order to use it in a specific fonction.

For exemple I want to convert the string

`'abc'`

`[['a'],['b'],['c']]`

so the script i wrote was:

`s='some string'`

t=[[0]]*len(s)

for i in range(len(s)):

t[i][0] = list(s)[i]

return t

the problem is that this returns

`[['g'],['g'],..,['g']]`

`[['s'],['o'],..,['g'])`

I found another way to achieve that, but i can't seem to find the problem of this script.

So,if anyone could help me, i would really appreciate it. Thanks in advance.

Answer Source

This is a classic mistake: `[[0]]*n`

creates a list of `n`

references to a unique object `[0]`

. Use this instead to create a list of `n`

different objects all equal to `[0]`

: `[[0] for i in range(n)]`

. This way, you can then change the value of each of them without affecting the others.