Python How to print list to list

Viewed 146

I have meet a problem of multiple output.

product_list=['Salted Egg Grade A','Salted Egg Grade B','Salted Egg Grade C']
price_list=['30','27','24']
for x in product_list:
  for y in price_list:
    print(x +": "+ y)

what I expected is

Salted Egg Grade A: 30
Salted Egg Grade B: 27
Salted Egg Grade C: 24

What I am getting is

Salted Egg Grade A: 30
Salted Egg Grade A: 27
Salted Egg Grade A: 24
Salted Egg Grade B: 30
Salted Egg Grade B: 27
Salted Egg Grade B: 24
Salted Egg Grade C: 30
Salted Egg Grade C: 27
Salted Egg Grade C: 24

Is there any solution to solve this?

5 Answers

You can use zip

product_list=['Salted Egg Grade A','Salted Egg Grade B','Salted Egg Grade C']
price_list=['30','27','24']
for x,y in zip(product_list, price_list):
    print(x + ": " + y)

Output:

Salted Egg Grade A: 30
Salted Egg Grade B: 27
Salted Egg Grade C: 24

You can also use enumerate() which basically returns the index as well as the element for each iteration. By using these indices you can loop on the other variable.

product_list=['Salted Egg Grade A','Salted Egg Grade B','Salted Egg Grade C']
price_list=['30','27','24']
for index, x in enumerate(product_list):
    print(x +": "+ price_list[index])

Try:

product_list=['Salted Egg Grade A','Salted Egg Grade B','Salted Egg Grade C']
price_list=['30','27','24']
for i in range(len(product_list)):
  print(product_list[i] +": "+price_list[i])

Output:

Salted Egg Grade A: 30
Salted Egg Grade B: 27
Salted Egg Grade C: 24

Don't use for loop here, it's not python way of printing the list. Make use of Zip() function. It takes two equal length list and merges them into a together.

When you printing more than one list better you can make use of ZIP() rather than ENUMERATE() or something else because zip() is the best and fast way to obtain your results. like

for x, y in zip(product_list, price_list):
     print(x + " " + y)
Related