Reputation: 45
I create a 2D list, here is what I tried
list = [[] for i in range(2)]
data = 'abcd'
for row in data:
for col in row:
list[:0] = data
I got
['a','b','c','d', 'a','b','c','d','a','b','c','d','a','b','c','d']
But what I want is
['a','b']
['c','d']
Anyone can help?
Upvotes: 0
Views: 21
Reputation: 5479
You can to this without iteration:
data = 'abcd'
r = [list(data[:2]) , list(data[2:])]
print(r)
#[['a', 'b'], ['c', 'd']]
Upvotes: 1
Reputation: 38
The following should work:
LIST_SIZE = 2
lists = [[] for _ in range(LIST_SIZE)]
data = 'abcd'
for i in range(LIST_SIZE):
for j in range(LIST_SIZE):
letter = data[LIST_SIZE * i + j]
lists[i].append(letter)
Upvotes: 0