0
itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]


print([f"Item {stock} : Price = {price}" for stock,price in itemlist]  )


for stock,price in itemlist:
  print(f"Item {stock} : Price = {price}")

how can i print list comprehension object one by one like for loop does?

I tried unpacking each item in list but couldn't able to do it.

how can unpack each item and print in a line by line format instead of of returing list.

i removed list and pyhton returns generator object how can i print that?

print(f"Item {stock} : Price = {price}" for stock,price in itemlist  )

Output:<generator object at 0x7fd0af2bc5d0>

Desired Output:

Item Tatamotors : Price = 483.4568

Item M&M : Price = 953.8045

Item TVSmotors : Price = 712

Item AshokLeyland : Price = 142.2567

Using LIST COMPREHENSION

uozcan12
  • 404
  • 1
  • 5
  • 13
vasu dev
  • 21
  • 5
  • 2
    `print(*(f"Item {stock} : Price = {price}" for stock,price in itemlist), sep='\n')` – Mechanic Pig May 29 '22 at 05:26
  • In fact, there is no benefit in doing so. – Mechanic Pig May 29 '22 at 05:27
  • Thanks Bro. Why there is no benefit? – vasu dev May 29 '22 at 05:33
  • 1
    In addition to reducing the number of lines of code, it does not bring any other benefits, and it will require you to generate all strings at once. If your list is large enough, it may crash your program. @vasu dev – Mechanic Pig May 29 '22 at 05:37
  • Does this answer your question? [Printing using list comprehension](https://stackoverflow.com/questions/37084246/printing-using-list-comprehension) – MohitC May 29 '22 at 06:16
  • No real use in list comprehension here, may want to look at https://stackoverflow.com/questions/8068251/why-is-python-list-comprehension-sometimes-frowned-upon – Thornily May 29 '22 at 06:27

2 Answers2

0
itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]

print('\n'.join([f"Item {stock} : Price = {price}" for stock,price in itemlist]))  

Output:

Item Tatamotors : Price = 483.4568
Item M&M : Price = 953.8045
Item TVSmotors : Price = 712
Item AshokLeyland : Price = 142.2567
uozcan12
  • 404
  • 1
  • 5
  • 13
0

You can print using List Comprehension, but I think it'll occupy useless memory, In big scale environment it's not the best practice. But ya there is the way below,

itemlist = [("Tatamotors",483.4568), ("M&M",953.8045),("TVSmotors",712),("AshokLeyland",142.2567)]
    
# Dummy list, which is no use other that printing
[print(f"Item {stock} : Price = {price}") for stock,price in itemlist] 

Output:

Item Tatamotors : Price = 483.4568
Item M&M : Price = 953.8045
Item TVSmotors : Price = 712
Item AshokLeyland : Price = 142.2567