Iterating through lists of lists in Python while keeping data structure

How can I iterate through lists of lists while keeping a lists data structure? Here is the case:

w = [3, 3]
z = [[1, 1, 1], [2, 2]]
lst = []

for x, y in zip(w, z):
    for u in y:
        lst.append(u+x)

print (lst)

What I get is: [4, 4, 4, 5, 5]
What I want is: [[4, 4, 4], [5, 5]]

I need to have the original list data structure.

Upvotes: 0

Views: 85

Answers (3)

Sharim09
Sharim09

Reputation: 6214

Try this.

w = [3, 3]
z = [[1, 1, 1], [2, 2]]
lst = []

for x, y in zip(w, z):
    for _ in range(len(z)):
        lst.append([u+x for u in y])

print(lst)

OUTPUT: [[4, 4, 4], [4, 4, 4], [5, 5], [5, 5]]

Upvotes: 2

Cardstdani
Cardstdani

Reputation: 5223

Based on the information available on the question, I think you should traverse both lists with an O(nxm) time complexity approximately adding the corresponding values between lists in order to preserve original data structure:

w = [3, 3]
z = [[1, 1, 1], [2, 2]]
lst = []

for i in z:
    for j in w:
        lst.append([a+j for a in i])
    
print (lst)

Output:

[[4, 4, 4], [4, 4, 4], [5, 5], [5, 5]]

Also, if you want it in one line, you can extend the use of list comprehension:

w = [3, 3]
z = [[1, 1, 1], [2, 2]]
lst = []

lst = [[a+j for a in i] for j in w for i in z]
print (lst)

Output: (In this case the order is changed, you can invert the execution order of the for loops to get the correct one if needed)

[[4, 4, 4], [5, 5], [4, 4, 4], [5, 5]]

Upvotes: 2

Anentropic
Anentropic

Reputation: 33853

As a one-liner:

import itertools

w = [3, 3]
z = [[1, 1, 1], [2, 2]]

lst = [[x + val for val in vals] for x, vals in itertools.product(w, z)]

print (lst)

Output:

[[4, 4, 4], [5, 5], [4, 4, 4], [5, 5]]

Upvotes: 0

Related Questions