2

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' to a : [['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']] instead of [['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.

1
  • I see, thank you guys :). Commented Jul 31, 2016 at 13:03

2 Answers 2

5

[[0]] * len(s) doesn't do what you think it does, consider this better approach:

s = 'abc'
li = [[ch] for ch in s]
print(li)
>> [['a'], ['b'], ['c']]
Sign up to request clarification or add additional context in comments.

1 Comment

You can add a condition in your comprehension to ignore whitespace too in order to just have all non-whitespace characters. But I guess it also depends on what characters are expected to be kept in the list.
3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.