'Printing from Class in python with list comprehension

Why does my print function from my Class work when I am using a loop, but return memory locations when I print using a list comprehension?

stocks= ['STY','STY','PRC','STY','PRC','STY','PRC','STY','PRC','STY']
price=[48,46,35,46,235,46,34,64,26,53]
quantity=[10,24,60,24,54,64,10,10,35,10]
type=['sell','sell','sell','sell','sell','buy','buy','buy','buy','buy']

data=list(zip(stocks,price,quantity,type))
print(list(data))


class Order():
    def __init__(self, stock_name, cost, quantity, trx_type):
        self.stock_name = stock_name
        self.cost = cost
        self.cost = cost
        self.quantity = quantity
        self.trx_type = trx_type
    
    def __str__(self):
        return '{stock}: {trx} {quant} at ${cost}'.format(stock = self.stock_name, trx = self.trx_type.title(), quant = self.quantity, cost = self.cost)

order_list=[]
for order in data:
    stock = Order(stock_name  = order[0], cost = order[1], quantity = order[2], trx_type = order[3])
    order_list.append(stock)
    
print([order for order in order_list])  ## This returns list of memory locations

for order in order_list:  ## this returns print statements from __str)__
    print(order)


Solution 1:[1]

[order for order in order_list]

Here you're storing instances in a list using list comprehension. And when you print them using:

print([order for order in order_list])

it prints the list of instances (not a single instance or instances one by one but a complete list). Since you have stored instances in the list, it will store their location.

Similarly when you use loop:

for order in order_list:
    print(order)

Now you're accessing single instances one by one and printing them and it will use the __str__() function of the class.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vishwa Mittar