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 merge two lists in python without using plus

I have two list in same size in python and want to merge them to become one list with the same number size as before

first one :

['add ', 'subtract ', 'multiply ', 'divide ']

second one :

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

[3, 2, 3, 2]

and i want output came like :

['add 3', 'subtract 2', 'multiply 3', 'divide 2']

How can I do that?

I tried this:

list3 = functions_name + main_function_count

but the output is :

['add ', 'subtract ', 'multiply ', 'divide ', 3, 2, 3, 2]

>Solution :

+ is adding the lists themselves, you want to apply + to each element.

ops = ['add ', 'subtract ', 'multiply ', 'divide ']
nums = [3, 2, 3, 2]
list3 = [op+str(n) for op, n in zip(ops, nums)]
# or using an fstring to remove "+" entirely
list3 = [f"{op}{n}" for op, n in zip(ops, nums)]

zip lets you iterate multiple "iterables", like lists, in parallel.

edit: changed n to str(n), fstring

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