0

This nested for loop accomplishes my goal but I would like to do it using list comprehension and/or lambda func

new_a=[]
new_b=[]
a=[1,2,3]
b=[1,2,3]

for num_a in a:
    for num_b in b:
        new_a.append(num_a)
        new_b.append(num_b)

print(new_a)
print(new_b)

output:

new_a=[1, 1, 1, 2, 2, 2, 3, 3, 3]

new_b=[1, 2, 3, 1, 2, 3, 1, 2, 3]

I can get new_a with [num for num in a for num in b]

but can't figure out how to get new_b using listcomp or lambda

6
  • 1
    Maybe: new_b = b * len(a) Commented Sep 7, 2020 at 19:57
  • [num_b for num_a in a for num_b in b]? Commented Sep 7, 2020 at 19:58
  • Agree with @MarkMeyer; sometimes you don’t need comprehension/loop/etc. Similar for new_a, if you wanted to use numpy: np.repeat([1,2,3], 3). Commented Sep 7, 2020 at 20:07
  • You seem to be looking for itertools.permutations Commented Sep 7, 2020 at 20:08
  • @S3DEV I'd be hesitant to include something as heavy weight as numpy for this unless it was already in the project, but generally agree. Commented Sep 7, 2020 at 20:10

3 Answers 3

1

What you really want to do is just use the length of the one array to perform the operation on the other. You could use for _ in range(len(old)), but just iterating over the list and ignoring the output performs the same thing. The trick here is the arrangement of for loops

old_a = [1, 2, 3]
old_b = [1, 2, 3]

new_a = [a for a in old_a for _ in old_b]
new_b = [b for _ in old_a for b in old_b]

print(new_a)
print(new_b)

Output

[1, 1, 1, 2, 2, 2, 3, 3, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use zip along with map function to do that:

new_a, new_b = map(list,zip(*[[num_a, num_b] for num_a in a for num_b in b]))

print(new_a)
print(new_b)

This will return:

[1, 1, 1, 2, 2, 2, 3, 3, 3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]

Comments

0

How about:

a=[1,2,3]
b=[1,2,3]

new_a=list(el for el1 in zip(* [a]*len(b)) for el in el1)
new_b=b*len(a)

Outputs:

>>> new_a
[1, 1, 1, 2, 2, 2, 3, 3, 3] 

>>> new_b
[1, 2, 3, 1, 2, 3, 1, 2, 3]

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.