1

I am trying to zip two lists together by iterating over them in a nested for loop but it is iterating over each character instead of the entire string. Here is what I have tried:

lengths = ['30', '15', '10']
tags = ['tom', 'tod']

combined = [list(zip(a,b)) for a in lengths for b in tags]
print(combined)

Output:

[[('3', 't'), ('0', 'o')], [('3', 't'), ('0', 'o')], [('1', 't'), ('5', 'o')], [('1', 't'), ('5', 'o')], [('1', 't'), ('0', 'o')], [('1', 't'), ('0', 'o')]]

The output I need:

[[('30'), ('tom')], [('30'), ('tod')], [('15'), ('tom')], [('15'), ('tod')], [('10'), ('tom')], [('10'), ('tod')]]

How can I accomplish this?

Andrew
  • 31
  • 4
  • The parentheses in your desired output are redundant; `('30')` is equivalent to `'30'`. – chepner Oct 21 '19 at 21:06
  • 2
    As such, you just need `[list(z) for z in itertools.product(lengths, tags)]`. Or just `[list((a, b)) for a in lengths for b in tags]`; drop the call to `zip`. – chepner Oct 21 '19 at 21:07
  • The problem here isn't with the iteration, but with the processing done each time through the loop. `list(zip(a,b))` here makes **no sense at all**. – Karl Knechtel Feb 18 '23 at 19:02

1 Answers1

4

You need a nested list comprehension:

result = [[length, tag] for length in lengths for tag in tags]
print(result)

Output

[['30', 'tom'], ['30', 'tod'], ['15', 'tom'], ['15', 'tod'], ['10', 'tom'], ['10', 'tod']]

Also as @chepner mentioned the parentheses are redundant, so you don't need them.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
  • 2
    That's not a nested list comprehension; `[length, tag]` is just a list literal, not a comprehension. – chepner Oct 21 '19 at 21:09