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
CodePudding user response:
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
CodePudding user response:
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