Can I iterate over complete strings in a list using a nested for loop?
Question:
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?
Answers:
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.
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?
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.