0

In the below sample code I'm not understanding why in my sent_message() I get output from smsg but not txt_msgs[0] Also not understanding why my sent_msg list remains empty?

txt_msgs = ['Mr Johnson, your new Cornwell Banks credit card is waiting for you at 13 High Street.', 'Boarding for your flight 320-YBO starts 12.11.2018 at 3:30pm. Enjoy your flight, Fair Airlines.', 'Booking confirmation: 4445789-YY. Millington Hotel is expecting you on 22.12.2018. Thank you for your order!']

sent_msg = []

def show_messages(txt_msgs):
    for msg in txt_msgs:
        print(f"\n{msg}")

def sent_messages(txt_msgs):
    for msg in txt_msgs:
        smsg = txt_msgs.pop()
        sent_msg.append(smsg)
        print(f"\n{smsg}")
        
#print(txt_msgs)
print(sent_msg)
#show_messages(txt_msgs)
sent_messages(txt_msgs)

Here's the output I get:

 []

Booking confirmation: 4445789-YY. Millington Hotel is expecting you on 22.12.2018. Thank you for your order!

Boarding for your flight 320-YBO starts 12.11.2018 at 3:30pm. Enjoy your flight, Fair Airlines.
[Finished in 0.0s]
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
  • [How to remove items from a list while iterating?](https://stackoverflow.com/q/1207406) – 001 Mar 10 '21 at 15:35

2 Answers2

1

Try this:

sent_msg = []
txt_msgs= ["Hey"]
def show_messages(txt_msgs):
    for msg in txt_msgs:
        print(f"\n{msg}")

def sent_messages(txt_msgs):
    for msg in txt_msgs:
        smsg = txt_msgs.pop()
        sent_msg.append(smsg)
        print(f"\n{smsg}")
        
        
#print(txt_msgs)
#Here it's empty 
print(sent_msg)
#show_messages(txt_msgs)
sent_messages(txt_msgs)
#Here the message is append to the list
print(sent_msg)

The problem is you printed sent_msg before anything was append to the it thus the list was empty

JACKDANIELS777
  • 339
  • 1
  • 14
  • These changes did make some improvement, however I thought the for loop would print all the messages in txt_msgs but it only printing the last message. I still don't understand why but when I uncomment out show_messages() that function print all 3 messages I expected the pop function to pop all 3 messages and append all 3 – Terry Turner Mar 10 '21 at 18:47
  • Once I removed the return sent_msg I got the output I was expecting – Terry Turner Mar 10 '21 at 21:07
1

Thats because your print sentmsg is called before the actual method call which adds data to the list.

Rahul Kumar
  • 87
  • 1
  • 12