Everyone, I wrote this simple program (to learn python) that prints a list of messages and then fills a new list of printed message. It’s very easy code , but something goes wrong with for loop.
The code is :
def Print_It (message):
print (message)
def Send_mex (To_send):
for sende in To_send:
Print_It(sende)
current_message = List_of_Message.pop()
Sended_message.append(current_message)
List_of_Message = ['GO!!!', 'WAIT!!!', 'DAMN!!', 'OUCH!!!']
Sended_message = []
Send_mex (List_of_Message)
Print_It (List_of_Message)
Print_It (Sended_message)
The Output is:
GO!!!
WAIT!!!
['GO!!!', 'WAIT!!!']
['OUCH!!!', 'DAMN!!']
The expected output is:
GO!!!
WAIT!!!
OUCH!!!
DAMN!!!
[]
['OUCH!!!', 'DAMN!!','GO!!!', 'WAIT!!!']
for some reasons that I don’t understand the for loop works only for two arguments of list not for all…
Any suggestions?
>Solution :
I can see you are a beginner, so I will try to make you work a little bit.
Try this script and try to understand it. I just added print so you can see what is going on with your List_of_Message and Sended_message.
def Print_It(message):
print(message)
def Send_mex(To_send):
for sende in To_send:
Print_It(sende)
print(f"Content of List_of_Message before pop : {List_of_Message}")
current_message = List_of_Message.pop()
print(f"Content of List_of_Message after pop : {List_of_Message}")
print(f"Content of Sended_message before append : {Sended_message}")
Sended_message.append(current_message)
print(f"Content of Sended_message after append : {Sended_message}")
print("\n\n")
List_of_Message = ["GO!!!", "WAIT!!!", "DAMN!!", "OUCH!!!"]
Sended_message = []
Send_mex(List_of_Message)
Print_It(List_of_Message)
Print_It(Sended_message)
I think you have understand that that pop() will remove the item from the list.
BUT
"The argument passed to the method is optional. If not passed, the default index -1 is passed as an argument (index of the last item)."
So if you don’t give an argument, it will remove the last items of the list.
Feel free to reach back if you still have issue or you still don’t understand why your for loop is finish early. I will edit to add more info if needed.