Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create lists from a cartesian product of two string lists

I have two string lists that look like this:

print(objects_list)
print(verb_list)

they output:

['parking_meter', 'sink', 'teddy_bear']
 
 ['sail', 'fill', 'fly', 'greet', 'hit', 'hose', 'hunt', 'install',
 'kick', 'launch', 'move', 'pick', 'repair', 'sit_at', 'squeeze',
 'stab', 'straddle', 'talk_on']

I want product of these two lists in a format that looks like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['parking_meter','sail'],['parking_meter','fill'],['parking_meter','fly']......]

I tried this code

list3 = [[str(l),str(n)] for l in objects_list for n in verb_list]
print(list3)

but it outputs:

[['[', '['], ['[', "'"], ['[', 's'], ['[', 'a'], ['[', 'i'], ['[',
 'l'], ['[', "'"], ['[', ','], ['[', ' '], ['[', "'"], ['[', 'f'],
 ['[', 'i'], ['[', 'l'], ['[', 'l'], ['[', "'"], ['[', ','], ['[', '
 '], ['[', "'"], ['[', 'f'], ['[', 'l'], ['[', 'y'], [.....

any solution?

>Solution :

From the output you get, it seems your input lists are strings, not lists.

As if objects_list was the output of print(objects_list), not the list itself.

Therefore, when iterating over objects_list, rather than interating over list items, you are iterating over the characters of its string reprensentation:

"["
"'"
"p"
"a"
...

Your code is otherwise correct, except you don’t need to cast the elements to string in the list comprehension.

list3 = [[l, n] for l in objects_list for n in verb_list]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading