Hon Wi Cong
Hon Wi Cong

Reputation: 141

Python How to print list to list

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?

Upvotes: 2

Views: 187

Answers (5)

Manukumar
Manukumar

Reputation: 225

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)

Upvotes: 1

Brian Destura
Brian Destura

Reputation: 12068

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

Upvotes: 7

Manukumar
Manukumar

Reputation: 225

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.

Upvotes: 1

Nisit
Nisit

Reputation: 71

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

Upvotes: 1

hafiz031
hafiz031

Reputation: 2670

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])

Upvotes: 2

Related Questions