Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate list elements into string in python

I have three lists and I want to concatenate each element from each list.

Here is what I tried:

quantity_list = ['6','4',7]
product_list = ['Apple','Orange','Grape']
uom_list = ['kg','kg','kg']
order_list = ""
order_list_temp = []
for ind,product in enumerate(product_list):
    order_list_temp.append(product + "-"+quantity_list[ind])
for ind,uom in enumerate(uom_list):
    order_list += order_list_temp[ind]+uom+"\n"

The expected output is:

Apple-6kg
Orange-4kg
Grape-7kg

It works as I expected but I want to know is there any other better solution.

like image 756
KbiR Avatar asked Jul 16 '26 19:07

KbiR


2 Answers

You can use zip:

>>> [f"{product}-{quantity}{uom}" for product, quantity, uom in zip(product_list, quantity_list, uom_list)]
['Apple-6kg', 'Orange-4kg', 'Grape-7kg']
like image 175
Selcuk Avatar answered Jul 19 '26 08:07

Selcuk


Using list comprehension:

order_list = '\n'.join(
    [ "{}-{}{}".format(p, q, u) for p, q, u in zip(product_list, quantity_list, uom_list) ]
)
like image 35
ilyankou Avatar answered Jul 19 '26 08:07

ilyankou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!