Gabriel
Gabriel

Reputation: 42439

Append to several lists inside list

I have an empty list of empty lists defined like so:

lis_A = [[], [], []]

to which I need, at some point in my code, to append values recursively like so:

lis_A[0].append(some_value0)
lis_A[1].append(some_value1)
lis_A[2].append(some_value2)

so it looks like this:

print lis_A
[[some_value0], [some_value1], [some_value2]]

What is the pythonic way of doing this?

Upvotes: 1

Views: 1246

Answers (3)

Viktor Kerkez
Viktor Kerkez

Reputation: 46636

>>> lis_A = [[], [], []]
>>> vals = [1,2,3]
>>> [x.append(y) for x, y in zip(lis_A, vals)]
>>> lis_A
[[1], [2], [3]]

Or if you wan't a fast for loop without side effects use:

from itertools import izip

for x, y in izip(lis_A, vals):
    x.append(y)

Upvotes: 3

Óscar López
Óscar López

Reputation: 236122

Try this:

lis_A = [[], [], []]
to_append = [1, 2, 3]

for i, e in enumerate(to_append):
    lis_A[i].append(e)

lis_A
=> [[1], [2], [3]]

If there's more than one element to append to each sublist, this will work as long as the to_append list is constructed with care:

lis_A = [[], [], []]
to_append = [1, 2, 3, 1, 2, 3]

for i, e in enumerate(to_append):
    lis_A[i % len(lis_A)].append(e)

lis_A
=> [[1, 1], [2, 2], [3, 3]]

Upvotes: 3

Brent Washburne
Brent Washburne

Reputation: 13158

I'd use a dictionary instead of a list:

my_lists = {}
for key, some_value in process_result():
    my_list = my_lists.get(key, [])
    my_list.append(some_value)
    my_lists[key] = my_list

There's probably some value for key that make sense, other than 0, 1, 2.

Upvotes: 0

Related Questions