I have variable like this :
message = "hello world"
and I want to put each 2 letters inside one list like this:
list = [['h', 'e'], ['l', 'l'], ...]
I have tried this method:
message = "hello world"
x,test = 0,[[]] * len(message)
for i in message:
if len(test[x]) >= 2:
x += 1
test[x].append(i)
else:
test[x].append(i)
but the result was adding hello world for every list.
The problem here is that your outer list contains a reference to a single inner list, just repeated. You can see what I mean by taking your resulting test
and reassigning the value of one of the elements:
>>> test[1][0] = 9999
[[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd'],
[9999, 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']]
So even though x
is incrementing, you're still just appending to a single list object because your test
variable is a list of repeated references to the same object.
You can get around this by using a comprehension to initialize your test
variable:
test = [[] for _ in range(len(message))]
You can also use zip
and slicing to get what you want in a single line of code:
[[*z] for z in zip(s[0::2], s[1::2])]
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments